// sections.jsx — landing-page sections matching the production ATS spec:
// Hero · About · Why Apply · How to Join · Who Fits · Schedule · Transfer Facts · FAQ · Footer

// ── Inline SVG icon set ─────────────────────────────────────
const I = {
  arrow: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M5 12h14M13 5l7 7-7 7" /></svg>,
  up: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 19V5M5 12l7-7 7 7" /></svg>,
  check: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M5 12l5 5L20 7" /></svg>,
  shield: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" /></svg>,
  flame: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 22c4 0 7-3 7-7 0-2-1-4-2-5-1 2-3 2-3 2 1-4-1-7-4-9 1 4-1 6-3 8s-2 4-2 4c0 4 3 7 7 7z" /></svg>,
  users: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M17 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2M9.5 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM23 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75" /></svg>,
  gift: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M20 12v10H4V12M2 7h20v5H2zM12 22V7M12 7H7.5a2.5 2.5 0 1 1 0-5C11 2 12 7 12 7zM12 7h4.5a2.5 2.5 0 1 0 0-5C13 2 12 7 12 7z" /></svg>,
  globe: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><circle cx="12" cy="12" r="10" /><path d="M2 12h20M12 2a15 15 0 0 1 0 20M12 2a15 15 0 0 0 0 20" /></svg>,
  chat: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M21 11.5a8.4 8.4 0 0 1-1 4 8.5 8.5 0 0 1-7.5 4.5 8.4 8.4 0 0 1-4-1L3 21l2-5.5a8.4 8.4 0 0 1-1-4A8.5 8.5 0 0 1 8.5 4a8.4 8.4 0 0 1 4-1A8.5 8.5 0 0 1 21 11.5z" /></svg>,
  bolt: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z" /></svg>,
  trophy: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M6 9H4a2 2 0 0 1-2-2V5h4M18 9h2a2 2 0 0 0 2-2V5h-4M6 5h12v6a6 6 0 0 1-12 0V5zM12 17v4M8 21h8" /></svg>,
  snow: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 2v20M2 12h20M4.5 4.5l15 15M19.5 4.5l-15 15" /></svg>,
  plus: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" {...p}><path d="M12 5v14M5 12h14" /></svg>,
  lock: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="3" y="11" width="18" height="11" rx="2" /><path d="M7 11V7a5 5 0 0 1 10 0v4" /></svg>,
  menu: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" {...p}><path d="M3 12h18M3 6h18M3 18h18" /></svg>,
  x: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" {...p}><path d="M18 6L6 18M6 6l12 12" /></svg>,
  vote: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M9 12l2 2 4-4M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10z" /></svg>,
  pin: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 22s8-9 8-13a8 8 0 1 0-16 0c0 4 8 13 8 13z" /><circle cx="12" cy="9" r="3" /></svg>
};

// ── Hero ───────────────────────────────────────────────────
// Helpers — parse "4.2B" / "92M" / "350K" → number, then format back
function parsePowerStr(s) {
  if (!s) return 0;
  const m = String(s).trim().match(/^([\d.]+)\s*([KMBT])?/i);
  if (!m) return 0;
  const n = parseFloat(m[1]);
  const u = (m[2] || '').toUpperCase();
  const mult = u === 'T' ? 1e12 : u === 'B' ? 1e9 : u === 'M' ? 1e6 : u === 'K' ? 1e3 : 1;
  return n * mult;
}
function formatPower(n) {
  if (n >= 1e12) return (n / 1e12).toFixed(1).replace(/\.0$/, '') + 'T';
  if (n >= 1e9) return (n / 1e9).toFixed(1).replace(/\.0$/, '') + 'B';
  if (n >= 1e6) return (n / 1e6).toFixed(1).replace(/\.0$/, '') + 'M';
  if (n >= 1e3) return (n / 1e3).toFixed(0) + 'K';
  return String(n);
}

function useNapTotals() {
  const [alliances, setAlliances] = React.useState([]);
  React.useEffect(() => {
    if (window.ATS) ATS.loadAlliances().then(setAlliances).catch(() => {});
    return window.ATS ? ATS.onAlliancesChange(setAlliances) : undefined;
  }, []);
  const safeAlliances = Array.isArray(alliances) ? alliances : [];
  const totalPower = safeAlliances.reduce((sum, a) => sum + parsePowerStr(a.power_total), 0);
  const totalMembers = safeAlliances.reduce((sum, a) => sum + (a.member_count || 0), 0);
  return {
    napCount: safeAlliances.length,
    napLabel: 'NAP',
    powerStr: totalPower > 0 ? formatPower(totalPower) : '—',
    members: totalMembers
  };
}

function Hero({ variant, onJoin }) {
  const nap = useNapTotals();
  const Title = () => <>
    <EditableText fieldKey="hero.title.line1" label="Hero title · line 1">Transfer in.</EditableText>{' '}
    <EditableText fieldKey="hero.title.accent" label="Hero title · accent" as="span" className="accent">Take your spot.</EditableText>
  </>;
  const Sub = () =>
  <EditableText fieldKey="hero.sub" label="Hero subtitle" as="p" className="hero-sub" multiline>
      State 3802 is a coordinated home for serious Whiteout Survival players. Four alliances,
      one unified event calendar — and a transparent application process to get you in.
    </EditableText>;

  const CTA = () =>
  <div className="hero-cta">
      <button className="btn btn-primary" onClick={onJoin}>
        <EditableText fieldKey="hero.cta.primary" label="Hero · Primary CTA" as="span">Apply to join</EditableText>
        <I.arrow width="16" height="16" />
      </button>
      <a className="btn btn-ghost" href="#about">
        <EditableText fieldKey="hero.cta.secondary" label="Hero · Secondary CTA" as="span">Learn more</EditableText>
      </a>
    </div>;

  const Stats = () =>
  <div className="hero-stats">
      <div className="stat"><div className="num">{nap.powerStr}</div><div className="lbl">Total {nap.napLabel} power</div></div>
      <div className="stat"><div className="num">{nap.members}</div><div className="lbl">{nap.napLabel} members</div></div>
      <div className="stat"><div className="num">{nap.napCount}</div><div className="lbl">Alliances in NAP</div></div>
    </div>;


  if (variant === 'split') {
    return (
      <section className="hero hero-v2" id="hero">
        <div className="container">
          <div className="hero-grid">
            <div>
              <span className="eyebrow">State 3802 · Recruiting</span>
              <h1 style={{ marginTop: 18 }}><Title /></h1>
              <Sub />
              <CTA />
            </div>
            <div className="glass-strong" style={{ padding: 28 }}>
              <div style={{ fontSize: '0.78rem', letterSpacing: '0.15em', textTransform: 'uppercase', color: 'var(--ice)', fontWeight: 600, marginBottom: 18 }}>
                State snapshot
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }}>
                {[
                [nap.powerStr, 'Total ' + nap.napLabel + ' power'],
                [String(nap.members), nap.napLabel + ' members'],
                [String(nap.napCount), 'Alliances in ' + nap.napLabel],
                ['S4', 'Current season']].
                map(([n, l], i) =>
                <div key={i}>
                    <div style={{ fontFamily: 'Space Grotesk', fontSize: '2rem', fontWeight: 700, letterSpacing: '-0.04em', lineHeight: 1 }}>{n}</div>
                    <div style={{ fontSize: '0.82rem', color: 'var(--text-faint)', marginTop: 6 }}>{l}</div>
                  </div>
                )}
              </div>
              <div style={{ height: 1, background: 'var(--border)', margin: '22px 0' }} />
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '0.88rem', color: 'var(--text-dim)' }}>
                <span>Last KvK</span>
                <span style={{ color: 'var(--ice)', fontWeight: 600 }}>1st place · 2.1M kills</span>
              </div>
            </div>
          </div>
        </div>
      </section>);

  }

  if (variant === 'banner') {
    return (
      <section className="hero hero-v3" id="hero">
        <div className="container" style={{ textAlign: 'center' }}>
          <EditableText fieldKey="hero.eyebrow" label="Hero eyebrow" as="span" className="eyebrow">State 3802 · Recruiting</EditableText>
          <h1 style={{ marginTop: 18, maxWidth: 900, margin: '18px auto 0' }}><Title /></h1>
          <div style={{ maxWidth: 560, margin: '22px auto 30px' }}><Sub /></div>
          <div style={{ display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
            <button className="btn btn-primary" onClick={onJoin}>Apply to join <I.arrow width="16" height="16" /></button>
            <a className="btn btn-ghost" href="#about">Learn more</a>
          </div>
          <EditableImage fieldKey="hero.banner.image" label="Hero banner image" alt="State 3802 capital banner" className="banner glass" aspect={21/9} />
          <Stats />
        </div>
      </section>);

  }

  return (
    <section className="hero hero-v1" id="hero">
      <div className="container">
        <EditableText fieldKey="hero.eyebrow" label="Hero eyebrow" as="span" className="eyebrow">State 3802 · Recruiting</EditableText>
        <h1 style={{ marginTop: 24, maxWidth: 920, marginInline: 'auto' }}><Title /></h1>
        <Sub />
        <CTA />
        <Stats />
      </div>
    </section>);

}

// ── About ──────────────────────────────────────────────────
function About() {
  return (
    <section id="about">
      <div className="container">
        <div className="section-head">
          <EditableText fieldKey="about.eyebrow" label="About · eyebrow" as="span" className="eyebrow">About</EditableText>
          <EditableText fieldKey="about.title" label="About · headline" as="h2">An organized state for serious players.</EditableText>
        </div>
        <div className="about-grid">
          <div>
            <EditableText fieldKey="about.body.p1" label="About · paragraph 1" as="p" multiline>
              State 3802 is built around four coordinated alliances under one unified event
              calendar. Officers across every major timezone, a private intel channel for
              cross-state movements, and zero tolerance for dead chats.
            </EditableText>
            <EditableText fieldKey="about.body.p2" label="About · paragraph 2" as="p" multiline>
              Transferring in is straightforward: submit an application, an R4 reviews it
              within 24 hours, and we send a state migration item once you're approved. You
              keep your character, gear, hero progression, VIP, and chiefs.
            </EditableText>
            <EditableText fieldKey="about.body.p3" label="About · paragraph 3" as="p" multiline>
              We don't approve transfers just to inflate numbers — every request gets reviewed.
              Quality over quantity, every time.
            </EditableText>
          </div>
          <div className="about-pillars">
            {[
            { icon: <I.shield />, h: 'Coordinated defense', p: 'Live rally calls during every Bear Trap, Crazy Joe, and KvK window.' },
            { icon: <I.users />, h: 'Active leadership', p: 'R4 officers online across all time zones. Real responses, not silence.' },
            { icon: <I.flame />, h: 'Competitive edge', p: 'Top-25 finishes in the last six KvK seasons. We play to win.' }].
            map((x, i) =>
            <div key={i} className="pillar glass">
                <div className="pillar-icon">{x.icon}</div>
                <div>
                  <h4>{x.h}</h4>
                  <p>{x.p}</p>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </section>);

}

// ── Why Apply ──────────────────────────────────────────────
const PERKS = [
{ icon: <I.gift />, h: 'Gift mail bombs', p: 'Daily alliance gifts at Lvl 5+, plus event-driven bonus rounds during peak windows.' },
{ icon: <I.shield />, h: 'Rally protection', p: 'Active R4s coordinate counter-rallies. You will never be solo-tanked overnight.' },
{ icon: <I.bolt />, h: 'Speedup pipeline', p: 'Help-spam culture and shared research priorities. Furnace 10 in record time.' },
{ icon: <I.users />, h: 'Veteran mentors', p: 'Paired guidance on troop comp, gear scoring, and chief charm priorities.' },
{ icon: <I.globe />, h: 'Global activity', p: '24/7 coverage across NA, EU, and APAC. Someone is always online for rallies.' },
{ icon: <I.trophy />, h: 'Top-tier rewards', p: 'Consistent top-3 alliance ranking = premium chest tiers every Sunday reset.' }];


function WhyApply({ layout }) {
  return (
    <section id="why-state">
      <div className="container">
        <div className="section-head">
          <EditableText fieldKey="why.eyebrow" label="Why apply · eyebrow" as="span" className="eyebrow">Why apply</EditableText>
          <EditableText fieldKey="why.title" label="Why apply · headline" as="h2">What you get for moving in.</EditableText>
          <EditableText fieldKey="why.sub" label="Why apply · sub" as="p" multiline>Concrete reasons to choose 3802 over staying where you are.</EditableText>
        </div>

        {layout === 'list' &&
        <div className="perks-list">
            {PERKS.map((x, i) =>
          <div key={i} className="perk-row">
                <div className="nm">{String(i + 1).padStart(2, '0')}</div>
                <div><h3>{x.h}</h3><p>{x.p}</p></div>
              </div>
          )}
          </div>
        }

        {layout === 'flow' &&
        <div className="perks-flow glass">
            {PERKS.slice(0, 4).map((x, i) =>
          <div key={i} className="perk-cell">
                <div className="perk-icon">{x.icon}</div>
                <h3>{x.h}</h3>
                <p style={{ color: 'var(--text-dim)', fontSize: '0.9rem' }}>{x.p}</p>
              </div>
          )}
          </div>
        }

        {layout === 'grid' &&
        <div className="perks-grid">
            {PERKS.map((x, i) =>
          <div key={i} className="perk-card glass">
                <div className="perk-icon">{x.icon}</div>
                <h3>{x.h}</h3>
                <p>{x.p}</p>
              </div>
          )}
          </div>
        }
      </div>
    </section>);

}

// ── How to Join (steps) ─────────────────────────────────────
const STEPS = [
{ n: 'STEP 01', h: 'Submit application', p: 'Fill out the form — IGN, state, power, optional coords, and any context the Transfer Manager should know.' },
{ n: 'STEP 02', h: 'Transfer Manager reviews', p: 'A Transfer Manager reviews your application and will contact you to coordinate next steps.' },
{ n: 'STEP 03', h: 'We assist with the move', p: 'We assist with each area of the transfer process and walk you through your next steps in-state.' }];


function HowToJoin({ onJoin }) {
  return (
    <section id="how-to-join">
      <div className="container">
        <div className="section-head">
          <EditableText fieldKey="howto.eyebrow" label="How to join · eyebrow" as="span" className="eyebrow">How to join</EditableText>
          <EditableText fieldKey="howto.title" label="How to join · headline" as="h2">Three steps to transfer in.</EditableText>
        </div>
        <div className="steps">
          {STEPS.map((s, i) =>
          <div key={i} className="step glass">
              <div className="n">{s.n}</div>
              <h4>{s.h}</h4>
              <p>{s.p}</p>
              {i < STEPS.length - 1 &&
            <div className="arrow"><I.arrow width="22" height="22" /></div>
            }
            </div>
          )}
        </div>
        <div style={{ display: 'flex', justifyContent: 'center', marginTop: 40 }}>
          <button className="btn btn-primary" onClick={onJoin} style={{ padding: '16px 28px', fontSize: '1rem' }}>
            Start your application <I.arrow width="16" height="16" />
          </button>
        </div>
      </div>
    </section>);

}

// ── Who Fits (power tiers) ──────────────────────────────────
function WhoFits() {
  return (
    <section id="who-fits">
      <div className="container">
        <div className="section-head">
          <span className="eyebrow">Who fits</span>
          <h2>Power tiers we're approving.</h2>
          <p>Power isn't everything, but it's our starting filter. Be honest about your tier — we approve across all three.</p>
        </div>
        <div className="req-row">
          <div className="req-card glass">
            <div className="tag">Tier 1 · Builder</div>
            <div className="num">6M+</div>
            <div className="lbl">FC1 path · learning rallies · placed in Iron Tundra</div>
          </div>
          <div className="req-card glass featured">
            <div className="tag">Tier 2 · Core</div>
            <div className="num">18M+</div>
            <div className="lbl">Rally-lead capable · active in KvK · placed in Aurora Pact</div>
          </div>
          <div className="req-card glass">
            <div className="tag">Tier 3 · Front line</div>
            <div className="num">35M+</div>
            <div className="lbl">Daily fights · veteran charm builds · placed in Frost Vanguard</div>
          </div>
        </div>
      </div>
    </section>);

}

// ── Schedule — grouped by Alliance ─────────────────────────
function Schedule() {
  const [alliances, setAlliances] = React.useState([]);
  const [events, setEvents] = React.useState([]);
  const [eventTimes, setEventTimes] = React.useState([]);
  const [zone, setZone] = React.useState('local'); // 'local' | 'utc'

  React.useEffect(() => {
    if (!window.ATS) return;
    ATS.loadAlliances().then(setAlliances).catch(() => {});
    ATS.loadEvents().then(setEvents).catch(() => {});
    ATS.loadEventTimes().then(setEventTimes).catch(() => {});
    const a = ATS.onAlliancesChange(setAlliances);
    const e = ATS.onEventsChange(setEvents);
    const t = ATS.onEventTimesChange(setEventTimes);
    return () => {a();e();t();};
  }, []);

  const tz = window.ATS ? ATS.timezoneShort() : '';

  // Format a single event_time slot — respects the Local/UTC toggle.
  // Never shows "Every 2 days" / recurrence labels — those live in admin only.
  const fmtTime = (slot) => {
    if (!slot || !slot.time_utc) return '—';
    const [h, m] = slot.time_utc.split(':').map(Number);
    if (isNaN(h) || isNaN(m)) return slot.time_utc + ' UTC';

    if (zone === 'utc') return slot.time_utc + ' UTC';

    // Local — use today's date in UTC as a reference, then re-format in the
    // viewer's locale. We intentionally don't try to roll forward to the next
    // weekday; the Day column shows that separately.
    const today = new Date();
    const ref = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate(), h, m));
    return ref.toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' });
  };

  const fmtDay = (slot) => {
    if (!slot) return '';
    if (slot.day_of_week) return ATS.dayShortName(slot.day_of_week);
    return '';
  };

  // Group by alliance → list of events with slots
  const safeAlliances = Array.isArray(alliances) ? alliances : [];
  const safeEvents = Array.isArray(events) ? events : [];
  const safeEventTimes = Array.isArray(eventTimes) ? eventTimes : [];
  const byAlliance = safeAlliances.
  filter((a) => a.is_recruiting || safeEventTimes.some((et) => et.alliance_id === a.id)).
  map((al) => ({
    al,
    rows: safeEvents.
    map((ev) => ({
      ev,
      slots: safeEventTimes.
      filter((et) => et.event_id === ev.id && et.alliance_id === al.id).
      sort((x, y) => (x.subtype || '').localeCompare(y.subtype || ''))
    })).
    filter((r) => r.slots.length > 0)
  })).
  filter((a) => a.rows.length > 0);

  return (
    <section id="schedule">
      <div className="container">
        <div className="section-head">
          <span className="eyebrow">Schedule</span>
          <h2>Live event calendar by alliance.</h2>
          <p>
            Each alliance schedules its events on its own clock. This grid is the single source
            of truth — what an R4 changes in admin shows up here within a second.
          </p>
          <div className="nap-tz">
            <I.globe width="13" height="13" />
            Times in
            <span className="nap-tz-toggle">
              <button className={zone === 'local' ? 'on' : ''} onClick={() => setZone('local')}>
                Local{tz ? ' · ' + tz : ''}
              </button>
              <button className={zone === 'utc' ? 'on' : ''} onClick={() => setZone('utc')}>UTC</button>
            </span>
          </div>
        </div>

        <div className="ally-sched-blocks">
          {byAlliance.length === 0 &&
          <div className="glass" style={{ padding: 36, textAlign: 'center', color: 'var(--text-faint)' }}>
              No event times configured yet. Officers can schedule events in the admin panel.
            </div>
          }
          {byAlliance.map(({ al, rows }) =>
          <div key={al.id} className="ally-sched-block glass">
              <div className="ally-sched-head">
                <div className="ally-sched-mark">{al.tag || al.name.slice(0, 3).toUpperCase()}</div>
                <div className="ally-sched-info">
                  <h3>{al.name}</h3>
                  <div className="ally-sched-meta">
                    {al.leader && <span><b>R5</b> {al.leader}</span>}
                    {al.power_total && <span>{al.power_total} power</span>}
                    {typeof al.member_count === 'number' && <span>{al.member_count} members</span>}
                    {al.power_requirement && <span>Min {al.power_requirement}</span>}
                  </div>
                </div>
              </div>
              <div className="ally-sched-tbl">
                <div className="ally-sched-row head">
                  <div>Event</div>
                  <div>Name</div>
                  <div>Day</div>
                  <div>Time</div>
                  <div></div>
                </div>
                {rows.flatMap(({ ev, slots }) => {
                const meta = window.ATS ? ATS.eventTypeMeta(ev.event_type) : null;
                return slots.map((s) =>
                <div key={s.id} className="ally-sched-row">
                      <div className="ally-sched-evt">
                        <span className="ally-sched-icon">{meta?.icon || '⭐'}</span>
                        {ev.name}
                      </div>
                      <div className="ally-sched-name">{s.subtype || '—'}</div>
                      <div className="ally-sched-day">{fmtDay(s) || <span style={{ color: 'var(--text-faint)' }}>—</span>}</div>
                      <div className="ally-sched-time">{fmtTime(s)}</div>
                      <div>{s.is_voting ? <span className="sched-vote"><I.vote width="11" height="11" /> Voting</span> : null}</div>
                    </div>
                );
              })}
              </div>
            </div>
          )}
        </div>
      </div>
    </section>);

}

// ── Transfer Facts ──────────────────────────────────────────
const TRANSFER_FACTS = [
{ k: '< 24h', lbl: 'Average review time', sub: 'From application to officer decision.' },
{ k: 'Day 30', lbl: 'Account age required', sub: 'Standard WoS migration item rule.' },
{ k: '100%', lbl: 'Progress preserved', sub: 'Furnace, gear, heroes, VIP, chiefs.' },
{ k: '11 langs', lbl: 'Officer support', sub: 'EN, ES, ZH, RU, PT, FR, NL, DE, UK, AR, KO.' }];


const RULES = [
{ h: 'Daily activity', p: 'Log in daily during event windows. 3 missed days = removal warning.' },
{ h: 'Discord required', p: 'Verify in our server within 72 hours of accepting your alliance invite.' },
{ h: 'No solo aggression', p: 'No initiating fights with friendly states. Defense is always welcome.' },
{ h: 'Honor NAPs', p: 'Respect non-aggression pacts. R4s coordinate all diplomatic moves.' },
{ h: 'Shield up off-events', p: 'No bubbleless overnight unless on rally duty or actively reinforcing.' },
{ h: 'Respect the chat', p: 'No politics, no slurs, no harassment. Disagreements happen in DMs.' }];


function TransferFacts() {
  return (
    <section id="transfer-facts">
      <div className="container">
        <div className="section-head">
          <span className="eyebrow">Transfer facts</span>
          <h2>What changes, what doesn't.</h2>
          <p>Everything you need to know about the migration process before you commit.</p>
        </div>

        <div className="tf-stats">
          {TRANSFER_FACTS.map((f, i) =>
          <div key={i} className="tf-stat glass">
              <div className="tf-big">{f.k}</div>
              <div className="tf-lbl">{f.lbl}</div>
              <div className="tf-sub">{f.sub}</div>
            </div>
          )}
        </div>

        <div className="tf-rules-head">
          <h3>House rules</h3>
          <p>Simple, enforced consistently. Read before you apply.</p>
        </div>
        <div className="rules">
          {RULES.map((r, i) =>
          <div key={i} className="rule glass">
              <div className="ck"><I.check width="14" height="14" /></div>
              <div>
                <h4>{r.h}</h4>
                <p>{r.p}</p>
              </div>
            </div>
          )}
        </div>
      </div>
    </section>);

}

// ── FAQ (pulled from ATS faq_items) ────────────────────────
function FAQ() {
  const [items, setItems] = React.useState([]);
  React.useEffect(() => {
    if (!window.ATS) return;
    ATS.loadFaqs().then(setItems).catch(() => {});
    return ATS.onFaqsChange(setItems);
  }, []);
  const safeItems = Array.isArray(items) ? items : [];
  const published = safeItems.filter((f) => f.published).sort((a, b) => (a.order_index || 0) - (b.order_index || 0));

  return (
    <section id="faq">
      <div className="container" style={{ maxWidth: 900 }}>
        <div className="section-head">
          <span className="eyebrow">FAQ</span>
          <h2>Common questions.</h2>
        </div>
        <div className="faq">
          {published.length === 0 &&
          <div style={{ color: 'var(--text-faint)', padding: 20 }}>No FAQ items yet.</div>
          }
          {published.map((f) =>
          <details key={f.id} className="q">
              <summary>
                <span>{f.question_en}</span>
                <span className="plus"><I.plus width="14" height="14" /></span>
              </summary>
              <p>{f.answer_en}</p>
            </details>
          )}
        </div>
      </div>
    </section>);

}

// ── Footer ──────────────────────────────────────────────────
function Footer({ onJoin }) {
  return (
    <footer className="footer" id="contact">
      <div className="container">
        <div className="footer-cta glass-strong">
          <EditableText fieldKey="footer.cta.eyebrow" label="Footer CTA · eyebrow" as="span" className="eyebrow">Ready to transfer?</EditableText>
          <EditableText fieldKey="footer.cta.title" label="Footer CTA · headline" as="h2" style={{ maxWidth: 720 }}>The Frostlands are colder when you're alone.</EditableText>
          <EditableText fieldKey="footer.cta.body" label="Footer CTA · body" as="p" multiline>Apply now or jump into Discord first to chat with our officers. We respond within 24 hours.</EditableText>
          <div className="row">
            <button className="btn btn-primary" onClick={onJoin}>Apply to join <I.arrow width="16" height="16" /></button>
            <a className="btn btn-ghost" href="#" onClick={(e) => {e.preventDefault();alert('Discord invite link placeholder');}}>
              <I.chat width="16" height="16" /> Join our Discord
            </a>
          </div>
        </div>
        <div className="footer-meta">
          <div>© 2026 State 3802 · 4wos.com · Whiteout Survival fan alliance · Not affiliated with the game publisher.</div>
          <div className="links">
            <a href="#about">About</a>
            <a href="#transfer-facts">Rules</a>
            <a href="#faq">FAQ</a>
            <a href="admin.html">Admin</a>
            <a href="#" onClick={(e) => e.preventDefault()}>Discord</a>
          </div>
        </div>
      </div>
    </footer>);

}

Object.assign(window, {
  Icons: I,
  Hero, About, WhyApply, HowToJoin, WhoFits, Schedule, TransferFacts, FAQ, Footer,
  // legacy aliases so older app.jsx references don't crash
  Perks: WhyApply, Power: WhoFits, Join: HowToJoin, NapAlliances: Schedule,
  Rules: () => null, Events: () => null, Achievements: () => null, Officers: () => null
});