// RWS — Home / Landing variations
// v1.2: HomeHero_Brief now pulls live player counts, queue, and map from /api/servers; nextWipe is computed from the schedule rule.
// v1.3: mobile pass — hero grids stack on ≤768px via useIsMobile,
//        padding/typography scale, server-connect strips and feature
//        blocks linearize, Discord CTA stacks. Desktop is unchanged.
// v1.4: live Discord stats via useDiscordStats — both hero variants now
//        render real member + online counts; replaced placeholder "3.1k" /
//        "3,140 members strong". Hero "Discord" pill is now an anchor that
//        actually opens the invite (was an inert button).
// v1.5: live numbers gated by isDiscordStatsVisible() — hidden until the
//        server crosses DISCORD_STATS_MIN_MEMBERS (50). Until then the
//        button just says "Discord", the dog-tag Members stat shows "—",
//        and the "JOIN THE DISCORD" band omits the LIVE stat row.
// v1.6: home cleanup — removed the "OPERATION BRIEF · 24 APR 2026 ·
//        CLASSIFICATION: OPEN / FILE · RWS—WEB—001" header strip above the
//        hero frame, the "CLEARED FOR DUTY" stamp under the mascot, and the
//        "ACTIVE DEPLOYMENTS" eyebrow above OUR SERVERS. SectionHead now
//        conditionally renders the eyebrow row so passing eyebrow="" (or
//        omitting it) collapses cleanly.
// v1.7: HomeHero_Brief — removed the "ACTIVE ROSTER" tape label from the
//        hero frame, and bumped the MascotBadge from 96/140 → 120/200 so
//        it fills the right-hand column more on desktop while still
//        scaling down cleanly on mobile.
// v1.8: HomeHero_Brief — further enlarged MascotBadge from 120/200 →
//        140/240 (mobile/desktop) per design feedback to better fill the
//        empty right-hand column.

const HomeHero_DogTag = ({ onNav }) => {
  const isMobile = useIsMobile();
  const live = useLiveServers();
  const discord = useDiscordStats();
  const merged = SERVERS.map(s => mergeLive(s, live));
  const [copied, setCopied] = useState(null);
  const copy = (txt, key) => {
    navigator.clipboard?.writeText(txt);
    setCopied(key);
    setTimeout(() => setCopied(null), 1500);
  };

  return (
    <div className="rws tx-canvas art-scroll" style={{ width: '100%', height: '100%', overflowX: 'hidden' }}>
      <NavBar active="home" onNav={onNav} />

      {/* Hero — big dog-tag */}
      <section style={{ padding: isMobile ? '32px 16px 28px' : '64px 60px 48px', position: 'relative' }}>
        <div style={{
          display: 'grid',
          gridTemplateColumns: isMobile ? '1fr' : '1.3fr 1fr',
          gap: isMobile ? 32 : 56,
          alignItems: 'center',
        }}>
          <div>
            <div style={{ display: 'flex', gap: 8, marginBottom: 20, flexWrap: 'wrap' }}>
              <span className="pill live">SERVERS ONLINE</span>
              <span className="pill">220 PLAYERS</span>
              <span className="pill warn">WIPE · 13D 04H</span>
            </div>
            <h1 style={{
              fontSize: isMobile ? 44 : 92, lineHeight: 0.95, margin: 0,
              color: 'var(--paper)',
              fontWeight: 700,
              letterSpacing: '0.02em',
            }}>
              CLOCK IN.<br />
              <span style={{ color: 'var(--blood-hot)' }}>BUILD.</span> RAID.<br />
              SURVIVE THE SHIFT.
            </h1>
            <p style={{ color: 'var(--od-200)', fontSize: isMobile ? 15 : 17, lineHeight: 1.6, marginTop: 20, maxWidth: 520 }}>
              Welcome to <strong style={{ color: 'var(--paper)' }}>Rusty Wage Slaves</strong> —
              a community for people who play Rust after work, between meetings,
              or instead of their spreadsheet. Two monthly-wipe servers, active admins,
              and a Discord full of people who've been there.
            </p>
            <div style={{
              display: 'flex',
              gap: 10,
              marginTop: 24,
              flexWrap: 'wrap',
              flexDirection: isMobile ? 'column' : 'row',
              alignItems: isMobile ? 'stretch' : 'flex-start',
            }}>
              <button className="btn primary" onClick={() => onNav('servers')}
                style={isMobile ? { justifyContent: 'center' } : {}}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z" /></svg>
                Join a server
              </button>
              <button className="btn" onClick={() => onNav('rules')}
                style={isMobile ? { justifyContent: 'center' } : {}}>
                Read the rules
              </button>
              <a href={discord?.invite || 'https://discord.gg/f5kBdjfDFR'}
                target="_blank" rel="noopener" className="btn ghost"
                style={isMobile ? { justifyContent: 'center' } : {}}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M19.27 5.33A14.64 14.64 0 0015 4l-.43.86a13.43 13.43 0 00-5.14 0L9 4a14.64 14.64 0 00-4.27 1.33 18.4 18.4 0 00-3.23 12.51A14.76 14.76 0 005.58 20l1-1.35a9.6 9.6 0 01-1.51-.72l.37-.27a10.43 10.43 0 009.12 0l.37.27a9.6 9.6 0 01-1.51.72l1 1.35a14.76 14.76 0 004.08-2.16 18.4 18.4 0 00-3.23-12.51z" /></svg>
                {isDiscordStatsVisible(discord)
                  ? `Discord · ${discord.members.toLocaleString()} · ${discord.online ?? 0} online`
                  : 'Discord'}
              </a>
            </div>

            {/* Server connect strip */}
            <div style={{ marginTop: isMobile ? 32 : 48, display: 'grid', gap: 12 }}>
              {merged.map((s) =>
              <div key={s.id} className="stencil-frame" style={{
                padding: isMobile ? '12px 14px' : '14px 18px',
                display: 'grid',
                gridTemplateColumns: isMobile ? '8px 1fr auto' : 'auto 1fr auto auto',
                alignItems: 'center', gap: isMobile ? 12 : 20,
              }}>
                  <div style={{
                  width: 8, height: isMobile ? 36 : 44,
                  background: s.color,
                  boxShadow: `0 0 8px ${s.color}88`
                }} />
                  <div style={{ minWidth: 0 }}>
                    <div className="stencil" style={{ fontSize: isMobile ? 14 : 16, color: 'var(--paper)' }}>{s.name}</div>
                    <div className="mono" style={{
                      fontSize: 11, color: 'var(--od-300)', marginTop: 4,
                      whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                    }}>
                      {s.url} · {s.players}/{s.maxPlayers} online
                    </div>
                  </div>
                  {!isMobile && (
                    <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                      <div style={{ width: 40, height: 4, background: 'var(--od-700)', borderRadius: 2, overflow: 'hidden' }}>
                        <div style={{ width: `${(s.players || 0) / (s.maxPlayers || 1) * 100}%`, height: '100%', background: s.color }} />
                      </div>
                    </div>
                  )}
                  <button className="btn primary" style={{ padding: isMobile ? '8px 12px' : '8px 14px', fontSize: 11 }}
                onClick={() => copy(`client.connect ${s.ip}`, s.id)}>
                    {copied === s.id ? '✓' : 'CONNECT'}
                  </button>
                </div>
              )}
            </div>
          </div>

          {/* Giant dog-tag */}
          <div style={{ position: 'relative', paddingTop: isMobile ? 32 : 20 }}>
            <div className="dog-tag" style={{
              transform: isMobile ? 'rotate(-1deg)' : 'rotate(-2deg)',
              padding: isMobile ? '24px 22px' : '32px 32px',
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 20 }}>
                <MascotBadge size={isMobile ? 70 : 92} />
                <div className="mono" style={{ fontSize: 9, color: 'var(--od-300)', letterSpacing: '0.2em', textAlign: 'right' }}>
                  ISSUE 00001<br />RWS—2026
                </div>
              </div>
              <div className="stencil" style={{ fontSize: isMobile ? 26 : 32, color: 'var(--paper)', letterSpacing: '0.08em', lineHeight: 1 }}>
                RUSTY<br />WAGE<br />SLAVES
              </div>
              <hr className="hr-stencil" style={{ margin: '20px 0' }} />
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, rowGap: 10 }}>
                <Stat label="Members" value={isDiscordStatsVisible(discord) ? discord.members.toLocaleString() : '—'} />
                <Stat label="Hours logged" value="184k" />
                <Stat label="Raids survived" value="12,402" />
                <Stat label="Heli Downed" value="1,847" />
              </div>
            </div>
            <div style={{ position: 'absolute', top: -14, right: isMobile ? 24 : 40, transform: 'rotate(4deg)', zIndex: 2 }}>
              <div className="tape">RWS COLLECTIVE</div>
            </div>
            <div style={{ position: 'absolute', bottom: 20, right: isMobile ? -10 : -30, zIndex: 2 }}>
              <div className="stamp">APPROVED</div>
            </div>
          </div>
        </div>
      </section>

      {/* About strip */}
      <section style={{
        padding: isMobile ? '40px 16px' : '56px 60px',
        borderTop: '1px solid var(--od-700)',
        background: 'var(--od-800)',
      }}>
        <div style={{
          display: 'grid',
          gridTemplateColumns: isMobile ? '1fr' : 'repeat(3, 1fr)',
          gap: isMobile ? 24 : 32,
        }}>
          <FeatureBlock n="01" title="Monthly wipes"
            body="Force wipe schedule only. We run 30-day wipes because life happens — you shouldn't lose your base because you took a weekend off." />
          <FeatureBlock n="02" title="Offline protection"
            body="Bases take 40% less damage when the entire team is offline. Play at 3am, sleep at 3pm — your loot will (probably) still be there." />
          <FeatureBlock n="03" title="Active admins, zero drama"
            body="Every admin plays legit. Reports are reviewed within 24 hours on Discord. No favoritism, no shadow-bans, no BS." />
        </div>
      </section>

      {/* Wipe schedule band */}
      <section style={{
        padding: isMobile ? '36px 16px' : '48px 60px',
        background: 'var(--od-900)',
      }}>
        <div style={{
          display: 'flex',
          flexDirection: isMobile ? 'column' : 'row',
          alignItems: isMobile ? 'flex-start' : 'center',
          justifyContent: 'space-between',
          gap: isMobile ? 18 : 0,
          marginBottom: 24,
        }}>
          <div>
            <div className="small-caps" style={{ color: 'var(--od-300)' }}>NEXT FORCE WIPE</div>
            <h2 style={{ fontSize: isMobile ? 28 : 40, margin: '8px 0 0' }}>
              {formatWipeDate(getNextWipe())}
            </h2>
          </div>
          <Countdown />
        </div>
        <div className="stencil-frame" style={{
          padding: isMobile ? 16 : 24,
          display: 'grid',
          gridTemplateColumns: isMobile ? 'repeat(2, 1fr)' : 'repeat(4, 1fr)',
          gap: isMobile ? 12 : 24,
        }}>
          {['APR', 'MAY', 'JUN', 'JUL'].map((m, i) =>
          <div key={m} style={{
            padding: isMobile ? 12 : 16,
            background: i === 1 ? 'rgba(179,48,48,0.1)' : 'var(--od-800)',
            border: `1px solid ${i === 1 ? 'var(--blood)' : 'var(--od-600)'}`,
            borderRadius: 2
          }}>
              <div className="mono" style={{ fontSize: 10, color: 'var(--od-300)', letterSpacing: '0.18em' }}>
                MONTH {i === 1 ? '· NEXT' : ''}
              </div>
              <div className="stencil" style={{ fontSize: isMobile ? 22 : 28, color: i === 1 ? 'var(--blood-hot)' : 'var(--paper)' }}>{m}</div>
              <div className="mono" style={{ fontSize: 11, color: 'var(--od-200)', marginTop: 6 }}>
                {['APR 02', 'MAY 07', 'JUN 04', 'JUL 02'][i]} · 18:00 UTC
              </div>
            </div>
          )}
        </div>
      </section>

      <SiteFooter onNav={onNav} />
    </div>);

};

function Stat({ label, value }) {
  return (
    <div>
      <div className="mono" style={{ fontSize: 9, color: 'var(--od-300)', letterSpacing: '0.2em', textTransform: 'uppercase' }}>{label}</div>
      <div className="stencil" style={{ fontSize: 20, color: 'var(--paper)', marginTop: 2 }}>{value}</div>
    </div>);
}

function FeatureBlock({ n, title, body }) {
  return (
    <div>
      <div className="stencil" style={{ fontSize: 44, color: 'var(--od-500)', letterSpacing: '0.04em', lineHeight: 1 }}>{n}</div>
      <h3 style={{ fontSize: 20, margin: '12px 0 10px' }}>{title}</h3>
      <p style={{ color: 'var(--od-200)', fontSize: 14, lineHeight: 1.6, margin: 0 }}>{body}</p>
    </div>);
}

// Live countdown driven by getNextWipe() — recomputed every second from the
// real wipe schedule (no drift, DST-aware via the helper).
function Countdown() {
  const isMobile = useIsMobile();
  const [tick, setTick] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setTick(t => t + 1), 1000);
    return () => clearInterval(id);
  }, []);
  const target = getNextWipe();
  const ms = Math.max(0, target.getTime() - Date.now());
  const d = Math.floor(ms / 86400000);
  const h = Math.floor((ms % 86400000) / 3600000);
  const m = Math.floor((ms % 3600000) / 60000);
  const s = Math.floor((ms % 60000) / 1000);
  return (
    <div style={{ display: 'flex', gap: isMobile ? 6 : 8 }}>
      {[['D', d], ['H', h], ['M', m], ['S', s]].map(([l, v]) =>
      <div key={l} style={{
        minWidth: isMobile ? 52 : 64,
        flex: isMobile ? 1 : 'none',
        padding: isMobile ? '8px 4px' : '10px 4px',
        background: 'var(--od-800)',
        border: '1px solid var(--od-600)',
        textAlign: 'center'
      }}>
          <div className="stencil" style={{ fontSize: isMobile ? 22 : 28, color: 'var(--blood-hot)', lineHeight: 1 }}>
            {String(v).padStart(2, '0')}
          </div>
          <div className="mono" style={{ fontSize: 9, color: 'var(--od-300)', letterSpacing: '0.2em', marginTop: 4 }}>{l}</div>
        </div>
      )}
    </div>);
}

// ─────────────────────────────────────────────
// VARIATION B — Server-first, data-dense (DEFAULT — wired in index.html)
// ─────────────────────────────────────────────
const HomeHero_Brief = ({ onNav }) => {
  const isMobile = useIsMobile();
  const [copied, setCopied] = useState(null);
  const live = useLiveServers();
  const discord = useDiscordStats();
  const copy = (txt, key) => {
    navigator.clipboard?.writeText(txt);
    setCopied(key);
    setTimeout(() => setCopied(null), 1500);
  };

  return (
    <div className="rws tx-canvas art-scroll" style={{ width: '100%', height: '100%', overflowX: 'hidden' }}>
      <NavBar active="home" onNav={onNav} />

      {/* Briefing-style hero */}
      <section style={{ padding: isMobile ? '24px 16px 16px' : '48px 60px 24px' }}>
        <div className="stencil-frame tx-grain" style={{
          padding: isMobile ? '32px 20px 28px' : '48px 48px 40px',
          position: 'relative',
        }}>
          <div style={{
            display: 'grid',
            gridTemplateColumns: isMobile ? '1fr' : '1fr auto',
            gap: isMobile ? 24 : 40,
            alignItems: 'center',
          }}>
            <div>
              <h1 style={{
                fontSize: isMobile ? 40 : 72,
                lineHeight: 0.95,
                margin: 0,
                color: 'var(--paper)',
              }}>
                CLOCK IN.<br />
                <span style={{ color: 'var(--blood-hot)' }}>BUILD.</span> RAID.<br />
                SURVIVE THE SHIFT.
              </h1>
              <p style={{ color: 'var(--od-200)', fontSize: isMobile ? 14 : 16, lineHeight: 1.7, marginTop: 20, maxWidth: 620 }}>
                Welcome to <strong style={{ color: 'var(--paper)' }}>Rusty Wage Slaves</strong> —
                a community for people who play Rust after work, between meetings,
                or instead of their spreadsheet. Two monthly-wipe servers, active admins,
                and a Discord full of people who've been there.
              </p>
              <div style={{
                display: 'flex',
                gap: 10,
                marginTop: 24,
                flexDirection: isMobile ? 'column' : 'row',
              }}>
                <button className="btn primary" onClick={() => onNav('servers')}
                  style={isMobile ? { justifyContent: 'center' } : {}}>
                  Browse servers
                </button>
                <a href="https://discord.gg/f5kBdjfDFR" target="_blank" rel="noopener" className="btn"
                  style={isMobile ? { justifyContent: 'center' } : {}}>
                  Join Discord
                </a>
              </div>
            </div>
            <div style={{
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              gap: 12,
              order: isMobile ? -1 : 0,
            }}>
              <MascotBadge size={isMobile ? 140 : 240} />
            </div>
          </div>
        </div>
      </section>

      {/* Server grid */}
      <section style={{ padding: isMobile ? '24px 16px 36px' : '32px 60px 56px' }}>
        <SectionHead title="OUR SERVERS" />
        <div style={{
          display: 'grid',
          gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr',
          gap: isMobile ? 16 : 20,
          marginTop: isMobile ? 18 : 24,
        }}>
          {SERVERS.map((s) => mergeLive(s, live)).map((s) =>
          <ServerCard key={s.id} s={s} copied={copied} copy={copy} />
          )}
        </div>
      </section>

      {/* Discord CTA */}
      <section style={{
        padding: isMobile ? '36px 16px' : '56px 60px',
        borderTop: '1px solid var(--od-700)',
      }}>
        <div className="stencil-frame" style={{
          padding: isMobile ? 24 : 40,
          display: 'flex',
          flexDirection: isMobile ? 'column' : 'row',
          justifyContent: 'space-between',
          alignItems: isMobile ? 'stretch' : 'center',
          gap: isMobile ? 20 : 32,
        }}>
          <div>
            <div className="small-caps" style={{ color: 'var(--amber)' }}>HQ · OFF-SERVER</div>
            <h2 style={{ fontSize: isMobile ? 26 : 36, margin: '6px 0 10px' }}>JOIN THE DISCORD</h2>
            <p style={{ color: 'var(--od-200)', fontSize: isMobile ? 14 : 15, lineHeight: 1.6, maxWidth: 560, margin: 0 }}>
              Wipe announcements, trade channels, VC for every server, and the #patch-notes
              channel that actually gets updated.
            </p>
            {isDiscordStatsVisible(discord) && (
              <div className="mono" style={{
                fontSize: 11, color: 'var(--amber)', letterSpacing: '0.2em',
                marginTop: 12,
              }}>
                <span className="pill live" style={{ marginRight: 8 }}>LIVE</span>
                {discord.members.toLocaleString()} MEMBERS · {discord.online ?? 0} ONLINE
              </div>
            )}
          </div>
          <a href="https://discord.gg/f5kBdjfDFR" target="_blank" rel="noopener" className="btn primary"
            style={{
              padding: isMobile ? '14px 18px' : '18px 28px',
              fontSize: isMobile ? 13 : 14,
              justifyContent: 'center',
              flexShrink: 0,
            }}>
            JOIN THE DISCORD →
          </a>
        </div>
      </section>

      <SiteFooter onNav={onNav} />
    </div>);

};

function SectionHead({ eyebrow, title }) {
  const isMobile = useIsMobile();
  return (
    <div>
      {eyebrow && (
        <div className="mono" style={{ fontSize: 10, color: 'var(--od-300)', letterSpacing: '0.3em' }}>{eyebrow}</div>
      )}
      <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginTop: eyebrow ? 8 : 0 }}>
        <h2 style={{ fontSize: isMobile ? 24 : 32, margin: 0 }}>{title}</h2>
        <hr className="hr-stencil" style={{ flex: 1 }} />
      </div>
    </div>);
}

function ServerCard({ s, copied, copy }) {
  const isMobile = useIsMobile();
  return (
    <div className="card notch" style={{ padding: isMobile ? 18 : 24, display: 'flex', flexDirection: 'column', gap: 18 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
        <div style={{ minWidth: 0 }}>
          <div style={{ display: 'flex', gap: 8, marginBottom: 10, flexWrap: 'wrap' }}>
            <span className="pill live">LIVE</span>
            <span className="pill" style={{ color: s.color, borderColor: s.color }}>{s.gather} · MAX {s.maxGroup}</span>
          </div>
          <h3 style={{ fontSize: isMobile ? 18 : 22, margin: 0, color: 'var(--paper)' }}>{s.name}</h3>
          <p style={{ color: 'var(--od-200)', fontSize: 13, margin: '6px 0 0' }}>{s.tagline}</p>
        </div>
        <div style={{
          width: 48, height: 48,
          background: 'var(--od-800)',
          border: `1px solid ${s.color}`,
          display: 'grid', placeItems: 'center',
          flexShrink: 0,
        }}>
          <div className="stencil" style={{ fontSize: 18, color: s.color }}>{s.id === 'solo' ? 'S' : 'Q'}</div>
        </div>
      </div>

      <div style={{
        display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14,
        padding: '14px 0', borderTop: '1px dashed var(--od-600)', borderBottom: '1px dashed var(--od-600)'
      }}>
        <KV k="Players" v={`${s.players}/${s.maxPlayers}${s.queue ? ` (+${s.queue})` : ''}`} />
        <KV k="Map" v={s.map} />
        <KV k="Next wipe" v={s.nextWipe} />
        <KV k="Wipe rule" v={s.wipe} />
      </div>

      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
        {s.features.map((f) =>
        <span key={f} className="mono" style={{
          fontSize: 10, color: 'var(--od-200)',
          padding: '3px 8px', background: 'var(--od-800)',
          border: '1px solid var(--od-600)',
          letterSpacing: '0.12em', textTransform: 'uppercase'
        }}>{f}</span>
        )}
      </div>

      <div style={{
        display: 'flex',
        gap: 8,
        alignItems: 'center',
        flexDirection: isMobile ? 'column' : 'row',
      }}>
        <div className="mono" style={{
          flex: 1,
          width: '100%',
          fontSize: 11, color: 'var(--od-200)',
          padding: '10px 12px',
          background: 'var(--od-900)',
          border: '1px solid var(--od-700)',
          letterSpacing: '0.08em',
          overflow: 'hidden',
          textOverflow: 'ellipsis',
          whiteSpace: 'nowrap',
        }}>
          {s.url}
        </div>
        <button className="btn primary" style={{
          padding: '10px 16px',
          fontSize: 12,
          width: isMobile ? '100%' : 'auto',
          justifyContent: 'center',
        }}
        onClick={() => copy(`client.connect ${s.ip}`, s.id)}>
          {copied === s.id ? '✓ COPIED' : 'CONNECT'}
        </button>
      </div>
    </div>);

}

function KV({ k, v }) {
  return (
    <div>
      <div className="mono" style={{ fontSize: 9, color: 'var(--od-300)', letterSpacing: '0.18em', textTransform: 'uppercase' }}>{k}</div>
      <div className="mono" style={{ fontSize: 13, color: 'var(--paper)', marginTop: 3 }}>{v}</div>
    </div>);
}

Object.assign(window, { HomeHero_DogTag, HomeHero_Brief, SectionHead, ServerCard, KV, Countdown });
