/* Home page -- mobile-first, dynamic & sporty.
   Sections: Ticker (from app shell), Hero, Next Up spotlight, Open Matches strip,
             How it works, Rules, Big CTA. */

const MAIN_BANNER = '/assets/images/main-banner-3.png';
const MOBILE_BANNER = '/assets/images/bpw-phone-banner.png';

function HomeHero({ onCTA }) {
  return (
    <section className="hero-section" style={{ position: 'relative', overflow: 'hidden' }}>
      {/* Static banner image -- desktop only, clickable to Prediction page */}
      <img src={MAIN_BANNER} alt="Predict now"
        role="button" tabIndex={0}
        className="hero-bg-img hide-mobile"
        onClick={() => onCTA('predict')}
        onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onCTA('predict'); } }}
        style={{
          position: 'absolute', top: 0, left: 0, width: '100%', height: '100%',
          objectFit: 'cover', objectPosition: 'center top', zIndex: 0, cursor: 'pointer',
        }}
      />
      {/* White gradient scrim -- mobile only (hidden on desktop) */}
      <div aria-hidden="true" className="hero-scrim only-mobile" style={{
        position: 'absolute', inset: 0, zIndex: 1, pointerEvents: 'none',
        background: 'linear-gradient(to right, rgba(255,255,255,0.94) 0%, rgba(255,255,255,0.80) 45%, rgba(255,255,255,0.20) 75%, rgba(255,255,255,0.05) 100%)',
      }} />

      <div className="hero-grid" style={{
        position: 'relative', zIndex: 2, minHeight: '60vh', maxWidth: 1200, margin: '0 auto',
        paddingLeft: 'clamp(16px, 4vw, 22px)', paddingRight: 'clamp(16px, 4vw, 22px)',
        display: 'grid', gridTemplateColumns: 'minmax(0, 1.15fr) minmax(0, 0.85fr)', gap: 'clamp(24px, 5vw, 56px)', alignItems: 'center',
        pointerEvents: 'none',
      }}>
        {/* Mobile hero banner, clickable to Prediction page -- mobile only (hidden on desktop) */}
        <div className="hero-logo-col only-mobile" style={{
          display: 'flex', alignItems: 'center', justifyContent: 'flex-start',
          position: 'relative', overflow: 'visible',
          marginLeft: '-18%',
          pointerEvents: 'auto',
        }}>
          <div className="mobile-hero-slide-wrap" style={{
            position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', overflow: 'hidden', zIndex: 0,
          }}>
            <img src={MOBILE_BANNER} alt="Predict now"
              role="button" tabIndex={0}
              onClick={() => onCTA('predict')}
              onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onCTA('predict'); } }}
              style={{
                width: '100%', height: '100%',
                objectFit: 'cover', objectPosition: 'center top',
                display: 'block', cursor: 'pointer',
              }}
            />
          </div>
        </div>
      </div>
    </section>
  );
}

function TicketCard() {
  return (
    <div className="floaty" style={{
      position: 'relative',
      transform: 'rotate(-1.5deg)',
      maxWidth: 380, justifySelf: 'end', width: '100%',
    }}>
      <div className="clip-stub" style={{
        background: '#fff',
        border: '2px solid var(--ink)',
        padding: 0,
        boxShadow: '10px 10px 0 0 var(--ink)',
      }}>
        <div style={{
          background: 'var(--ink)', color: '#fff', padding: '14px 22px',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase', fontWeight: 700,
        }}>
          <span style={{ color: 'var(--orange)' }}>Match day pass</span>
          <span className="font-mono" style={{ color: '#d4d4d8' }}>#WC-2026</span>
        </div>
        <div className="stripes-bg" style={{ height: 10 }} />
        <div style={{ padding: '22px 22px 16px' }}>
          <div className="font-display" style={{ fontSize: 22, lineHeight: 1.1, letterSpacing: '-0.01em' }}>
            FIFA World Cup<br />
            <span style={{ color: 'var(--orange)' }}>2026</span>
          </div>
          <div style={{
            marginTop: 8, fontSize: 12, letterSpacing: '0.18em', textTransform: 'uppercase',
            color: 'var(--grey-600)', fontWeight: 600,
          }}>
            USA · Canada · Mexico
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginTop: 18 }}>
            <Stat label="Outlets" value="04" />
            <Stat label="Matches" value="104" />
          </div>
          <div style={{
            margin: '20px -22px 0', borderTop: '2px dashed var(--grey-300)', position: 'relative',
          }}>
            <span style={{ position: 'absolute', left: -8, top: -10, width: 18, height: 18, background: '#fafafa', borderRadius: '50%' }} />
            <span style={{ position: 'absolute', right: -8, top: -10, width: 18, height: 18, background: '#fafafa', borderRadius: '50%' }} />
          </div>
          <div style={{ paddingTop: 14, fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--grey-500)', fontWeight: 600 }}>
            Brought to you by <span style={{ color: 'var(--ink)' }}>SunFront</span> · Quality &amp; Style
          </div>
        </div>
      </div>
    </div>
  );
}

function Stat({ label, value }) {
  return (
    <div style={{ border: '1.5px solid var(--ink)', padding: '10px 12px' }}>
      <div style={{ fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', fontWeight: 700, color: 'var(--grey-600)' }}>{label}</div>
      <div className="font-display" style={{ fontSize: 28, lineHeight: 1, marginTop: 4 }}>{value}</div>
    </div>
  );
}

/* ---------- Next-up spotlight ---------- */
function NextUpSpotlight({ onCTA }) {
  // Pick soonest OPEN match (all pre-kickoff matches are open)
  const candidate = useMemo(() => {
    return [...MATCHES].filter(m => m.status === 'OPEN').sort((a,b) => a.kickoffMs - b.kickoffMs)[0] || null;
  }, []);
  if (!candidate) return null;

  return (
    <section style={{ background: '#fff', padding: '0 0 0' }}>
      <div style={{ maxWidth: 1200, margin: '0 auto', padding: '0 22px' }}>
      <div className="next-up-card" style={{
        background: 'var(--ink)', color: '#fff',
        padding: '44px 28px',
        borderRadius: 12,
        position: 'relative', overflow: 'hidden',
        boxShadow: '0 8px 32px rgba(17,6,24,0.12)',
      }}>
      {/* diagonal stripe */}
      <div aria-hidden="true" style={{
        position: 'absolute', right: -60, top: -10, width: 320, height: 10,
        background: 'var(--orange)', transform: 'skewX(-12deg)',
      }} />
      <div aria-hidden="true" className="stripes-bg" style={{
        position: 'absolute', left: 0, right: 0, bottom: 0, height: 10, opacity: 0.95,
      }} />

      <div>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12 }}>
          <Eyebrow color="var(--orange)">Next up · Don't miss</Eyebrow>
          <div className="font-mono" style={{ fontSize: 11, color: 'var(--grey-400)', letterSpacing: '0.18em', textTransform: 'uppercase' }}>
            {candidate.stage}
          </div>
        </div>

        {/* Teams row: [Name A][Flag A]  VS  [Flag B][Name B] */}
        <div style={{ marginTop: 18, display: 'flex', alignItems: 'center', gap: 10, justifyContent: 'space-between' }}>
          <SpotTeam team={candidate.teamA} />
          <div style={{ flexShrink: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
            <VSHex size={52} />
          </div>
          <SpotTeam team={candidate.teamB} align="right" />
        </div>

        {/* Countdown + CTA - centered, aligns under flags */}
        <div style={{ display: 'grid', gap: 14, marginTop: 24 }}>
          <div className="font-mono" style={{ fontSize: 12, color: 'var(--grey-400)', letterSpacing: '0.18em', textTransform: 'uppercase', textAlign: 'center' }}>
            Pick before kickoff in
          </div>
          <BigCountdown to={candidate.kickoffMs} />
          <div style={{ display: 'flex', justifyContent: 'center', marginTop: 6 }}>
            <button onClick={() => onCTA('predict')} className="font-display btn-press" style={{
              background: 'var(--orange)', color: '#fff', border: 'none',
              borderRadius: 6,
              padding: '16px 32px', fontSize: 15, letterSpacing: '0.06em', textTransform: 'uppercase',
              boxShadow: '0 4px 16px rgba(241,86,35,0.30)',
              display: 'inline-flex', alignItems: 'center', gap: 10,
            }}>
              Lock my pick
              <Icon name="arrow" size={18} />
            </button>
          </div>
        </div>

        {/* Date/time + venue */}
        <div style={{ marginTop: 22, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
          <div style={{ fontSize: 13, color: '#fff', fontWeight: 600, letterSpacing: '0.04em', textAlign: 'center' }}>
            <Icon name="calendar" size={13} color="var(--orange)" />
            {' '}
            {(() => {
              const mvt = new Date(candidate.kickoffMs + 5 * 3600 * 1000);
              const days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
              const months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
              const d = days[mvt.getUTCDay()];
              const date = mvt.getUTCDate();
              const mon = months[mvt.getUTCMonth()];
              const yr = mvt.getUTCFullYear();
              const h24 = mvt.getUTCHours();
              const min = String(mvt.getUTCMinutes()).padStart(2, '0');
              const ampm = h24 >= 12 ? 'PM' : 'AM';
              const h12 = h24 % 12 || 12;
              return d + ', ' + date + ' ' + mon + ' ' + yr + ' · ' + h12 + ':' + min + ' ' + ampm + ' MVT';
            })()}
          </div>
          <div style={{ fontSize: 12.5, color: 'var(--grey-400)', textAlign: 'center', letterSpacing: '0.06em' }}>
            <Icon name="pin" size={12} color="var(--orange)" /> {candidate.venue}
          </div>
        </div>
      </div>
      </div>
      </div>
    </section>
  );
}

function SpotTeam({ team, align = 'left' }) {
  const isRight = align === 'right';
  return (
    <div style={{
      display: 'flex',
      flexDirection: isRight ? 'row' : 'row',
      alignItems: 'center',
      justifyContent: isRight ? 'flex-start' : 'flex-end',
      gap: 14, minWidth: 0, flex: 1,
    }}>
      {!isRight && (
        <div className="font-display" style={{ fontSize: 'clamp(16px, 3.5vw, 28px)', lineHeight: 1, letterSpacing: '-0.01em', textAlign: 'right', minWidth: 0 }}>
          {team.name}
        </div>
      )}
      <Flag code={team.flag} w={64} h={43} rounded={5} alt={team.name} />
      {isRight && (
        <div className="font-display" style={{ fontSize: 'clamp(16px, 3.5vw, 28px)', lineHeight: 1, letterSpacing: '-0.01em', textAlign: 'left', minWidth: 0 }}>
          {team.name}
        </div>
      )}
    </div>
  );
}

/* Big segmented countdown -- D / H / M / S with flip animation */
function BigCountdown({ to }) {
  const now = useNow(1000);
  const p = diffParts(to - now);
  const seg = (val, lbl) => (
    <div className="big-countdown-seg" style={{
      background: '#fff', color: 'var(--ink)',
      border: '1.5px solid var(--orange)',
      borderRadius: 8,
      minWidth: 'clamp(54px, 17vw, 76px)',
      padding: 'clamp(6px,2vw,10px) clamp(4px,1.5vw,8px) clamp(4px,1.5vw,6px)',
      display: 'flex', flexDirection: 'column', alignItems: 'center',
      boxShadow: '0 4px 12px rgba(241,86,35,0.15)',
      perspective: 300,
      flex: '1 1 0',
    }}>
      <span
        key={val}
        className="font-display seg-value"
        style={{
          fontSize: 'clamp(20px, 6vw, 44px)', lineHeight: 1, letterSpacing: '-0.02em',
          display: 'inline-block',
          animation: 'flipDigit 0.35s cubic-bezier(.2,.7,.2,1)',
        }}>
        {pad(val)}
      </span>
      <span className="seg-label" style={{ fontSize: 'clamp(8px,2vw,10px)', letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--grey-600)', fontWeight: 700, marginTop: 4 }}>{lbl}</span>
    </div>
  );
  const colon = <span className="font-display big-countdown-colon" style={{ color: 'var(--orange)', fontSize: 'clamp(18px,5vw,28px)', alignSelf: 'center', flexShrink: 0 }}>:</span>;
  return (
    <div className="big-countdown" style={{ display: 'flex', alignItems: 'center', gap: 'clamp(4px,2vw,8px)', justifyContent: 'center', flexWrap: 'nowrap' }}>
      {p.d > 0 && <>{seg(p.d, 'Days')}{colon}</>}
      {seg(p.h, 'Hrs')}{colon}
      {seg(p.m, 'Min')}{colon}
      {seg(p.s, 'Sec')}
    </div>
  );
}

/* ---------- Prizes ---------- */
const PRIZES = [
  { img: '/assets/images/prize-01.png', alt: 'Daily Pizza for 2 Winners' },
  { img: '/assets/images/prize-02.png', alt: 'Exciting Prizes Every Week' },
  { img: '/assets/images/prize-03.png', alt: 'Grand Prize Voucher -- MVR 50,000 SunFront Gift Voucher' },
];

function PrizesSection() {
  return (
    <section style={{ background: '#fff', padding: '48px 0 8px' }}>
      <div style={{ maxWidth: 1200, margin: '0 auto', padding: '0 22px' }}>
        <Eyebrow>What you can win</Eyebrow>
        <h2 className="font-display" style={{ fontSize: 'clamp(28px, 5vw, 46px)', lineHeight: 1, margin: '12px 0 28px', letterSpacing: '-0.02em' }}>
          Three types of Prizes for you.
        </h2>
        <div className="prizes-grid" style={{
          display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16,
        }}>
          {PRIZES.map(p => <PrizeCard key={p.img} {...p} />)}
        </div>
      </div>
    </section>
  );
}

function PrizeCard({ img, alt }) {
  return (
    <div className="lift lift-hover" style={{
      background: '#fff',
      border: '1px solid var(--grey-200)',
      borderRadius: 10,
      overflow: 'hidden',
      boxShadow: '0 2px 10px rgba(17,6,24,0.06)',
      aspectRatio: '375 / 180',
    }}>
      <img src={img} alt={alt}
        style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}
      />
    </div>
  );
}

/* ---------- Open matches strip (horizontal scroll on mobile, grid on desktop) ---------- */
/* Upcoming fixtures preview -- next 6 open/scheduled matches */
function FullScheduleSection({ onCTA }) {
  const upcoming = React.useMemo(() => {
    return [...MATCHES]
      .filter(m => m.status === 'OPEN' || m.status === 'SCHEDULED')
      .sort((a, b) => a.kickoffMs - b.kickoffMs)
      .slice(0, 6);
  }, []);

  const totalOpen = MATCHES.filter(m => m.status === 'OPEN').length;

  return (
    <section style={{ background: 'var(--grey-50)', padding: '56px 0 48px' }}>
      <div style={{ maxWidth: 1200, margin: '0 auto', padding: '0 22px' }}>

        {/* Header */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', flexWrap: 'wrap', gap: 16, marginBottom: 24 }}>
          <div>
            <Eyebrow>Coming up next</Eyebrow>
            <h2 className="font-display" style={{ fontSize: 'clamp(26px, 5vw, 40px)', lineHeight: 1, margin: '10px 0 0', letterSpacing: '-0.02em' }}>
              Matches to predict.
            </h2>
          </div>
          <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
            <span style={{ fontSize: 13, color: 'var(--grey-500)', display: 'inline-flex', alignItems: 'center', gap: 6 }}>
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--success)', display: 'inline-block' }} />
              {totalOpen} open now
            </span>
            <button onClick={() => onCTA('fixtures')} className="font-display btn-press-ink" style={{
              background: '#fff', color: 'var(--ink)', border: '1.5px solid var(--ink)', borderRadius: 6,
              padding: '10px 18px', fontSize: 12, letterSpacing: '0.06em', textTransform: 'uppercase',
              display: 'inline-flex', alignItems: 'center', gap: 7, cursor: 'pointer',
            }}>
              All fixtures <Icon name="arrow" size={14} />
            </button>
          </div>
        </div>

        {/* Match rows */}
        <div style={{ background: '#fff', border: '1px solid var(--grey-200)', borderRadius: 10, overflow: 'hidden' }}>
          {upcoming.length === 0 ? (
            <div style={{ padding: '32px', textAlign: 'center', color: 'var(--grey-400)', fontSize: 14 }}>
              No upcoming matches right now. Check back soon.
            </div>
          ) : upcoming.map((m, i) => {
            const mvt = new Date(m.kickoffMs + 5 * 3600 * 1000);
            const days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
            const months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
            const dateStr = days[mvt.getUTCDay()] + ', ' + months[mvt.getUTCMonth()] + ' ' + mvt.getUTCDate();
            const h24 = mvt.getUTCHours();
            const min = String(mvt.getUTCMinutes()).padStart(2, '0');
            const timeStr = (h24 % 12 || 12) + ':' + min + ' ' + (h24 >= 12 ? 'PM' : 'AM');
            const isLast = i === upcoming.length - 1;
            return (
              <button
                key={m.id}
                onClick={() => onCTA('predict')}
                className="fixture-row"
                style={{
                  width: '100%', background: 'none', border: 'none',
                  borderBottom: isLast ? 'none' : '1px solid var(--grey-100)',
                  padding: '14px 18px', cursor: 'pointer', textAlign: 'left',
                  display: 'grid',
                  gridTemplateColumns: '100px 1fr auto',
                  alignItems: 'center', gap: 16,
                  transition: 'background 0.1s',
                }}
                onMouseEnter={(e) => { e.currentTarget.style.background = 'var(--orange-50)'; }}
                onMouseLeave={(e) => { e.currentTarget.style.background = 'none'; }}
                aria-label={m.teamA.name + ' vs ' + m.teamB.name + ' - click to predict'}
              >
                {/* Date / time MVT */}
                <div style={{ flexShrink: 0, whiteSpace: 'nowrap' }}>
                  <div className="font-mono" style={{ fontSize: 10.5, fontWeight: 700, color: 'var(--grey-500)', letterSpacing: '0.06em', textTransform: 'uppercase', whiteSpace: 'nowrap' }}>
                    {dateStr}
                  </div>
                  <div className="font-mono" style={{ fontSize: 13, color: 'var(--ink)', fontWeight: 700, marginTop: 2, whiteSpace: 'nowrap' }}>
                    {timeStr}<sub style={{ fontSize: 8, color: 'var(--orange)', fontWeight: 800, letterSpacing: '0.08em', verticalAlign: 'sub', marginLeft: 2 }}>MVT</sub>
                  </div>
                </div>

                {/* Teams */}
                <div className="fixture-teams" style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
                  <div className="fixture-team" style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
                    <Flag code={m.teamA.flag} w={28} h={20} rounded={3} alt={m.teamA.name} />
                    <span className="font-display fixture-name" style={{ fontSize: 'clamp(13px, 2.2vw, 15px)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                      {m.teamA.name}
                    </span>
                  </div>
                  <span className="fixture-vs" style={{ fontSize: 10, fontWeight: 700, color: 'var(--grey-300)', flexShrink: 0, letterSpacing: '0.1em' }}>VS</span>
                  <div className="fixture-team" style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
                    <Flag code={m.teamB.flag} w={28} h={20} rounded={3} alt={m.teamB.name} />
                    <span className="font-display fixture-name" style={{ fontSize: 'clamp(13px, 2.2vw, 15px)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                      {m.teamB.name}
                    </span>
                  </div>
                </div>

                {/* Pick badge */}
                <span style={{
                  flexShrink: 0, display: 'inline-flex', alignItems: 'center', gap: 5,
                  background: 'var(--orange)', color: '#fff',
                  fontSize: 11, fontWeight: 800, padding: '5px 12px', borderRadius: 5,
                  letterSpacing: '0.06em', textTransform: 'uppercase',
                }}>
                  Pick <Icon name="arrow" size={11} color="#fff" />
                </span>
              </button>
            );
          })}

          {/* Footer link */}
          <div style={{ borderTop: '1px solid var(--grey-100)', padding: '12px 18px', background: 'var(--grey-50)', display: 'flex', justifyContent: 'center' }}>
            <button onClick={() => onCTA('fixtures')} style={{
              background: 'none', border: 'none', cursor: 'pointer',
              fontSize: 12, fontWeight: 700, color: 'var(--grey-600)',
              letterSpacing: '0.08em', textTransform: 'uppercase',
              display: 'inline-flex', alignItems: 'center', gap: 6,
            }}>
              See all 104 fixtures <Icon name="arrow" size={13} color="var(--grey-600)" />
            </button>
          </div>
        </div>

      </div>
    </section>
  );
}

/* ---------- How it works ---------- */
const STEPS = [
  { n: '01', t: 'Shop at SunFront',  icon: 'receipt', d: 'Any purchase over MVR 1,000 qualifies. Save your receipt.' },
  { n: '02', t: 'Enter your bill',   icon: 'message', d: 'Type your bill number and mobile. 30 seconds, done.' },
  { n: '03', t: 'Predict the Match', icon: 'target',  d: 'Team A, Draw, or Team B. 104 matches to call.' },
  { n: '04', t: 'Enter the draw',    icon: 'trophy',  d: 'Correct pick = draw entry. More games, more chances.' },
];

function HowItWorks() {
  return (
    <section style={{ background: '#fff', padding: '72px 0 40px' }}>
      <div style={{ maxWidth: 1200, margin: '0 auto', padding: '0 22px' }}>
        <div style={{ display: 'flex', alignItems: 'end', justifyContent: 'space-between', flexWrap: 'wrap', gap: 16 }}>
          <div>
            <Eyebrow>How it works</Eyebrow>
            <h2 className="font-display" style={{ fontSize: 'clamp(28px, 5vw, 46px)', lineHeight: 1, margin: '14px 0 0', letterSpacing: '-0.02em' }}>
              Four steps. Free entry.
            </h2>
          </div>
          <p style={{ color: 'var(--grey-600)', maxWidth: 320, margin: 0, fontSize: 14, lineHeight: 1.5 }}>
            No app. No signup. Just your SunFront receipt.
          </p>
        </div>

        <div className="step-grid" style={{
          display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginTop: 36,
        }}>
          {STEPS.map(s => <StepCard key={s.n} {...s} />)}
        </div>
      </div>
    </section>
  );
}

function StepCard({ n, t, icon, d }) {
  return (
    <div className="lift lift-hover" style={{
      position: 'relative',
      background: '#fff',
      border: '1px solid var(--grey-200)',
      borderRadius: 10,
      padding: '24px 20px 20px',
      boxShadow: '0 2px 10px rgba(17,6,24,0.06)',
      overflow: 'hidden',
    }}>
      <div className="clip-tri-tr font-display" style={{
        position: 'absolute', top: 0, right: 0, width: 76, height: 76, background: 'var(--orange)',
        color: '#fff', fontSize: 17, padding: 8, display: 'flex', justifyContent: 'flex-end',
      }}>
        {n}
      </div>
      <div style={{
        width: 52, height: 52, background: 'var(--ink)', color: '#fff',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        transform: 'rotate(-3deg)',
        marginBottom: 18,
      }}>
        <Icon name={icon} size={26} color="var(--orange)" stroke={2} />
      </div>
      <div className="font-display" style={{ fontSize: 18, letterSpacing: '-0.01em', marginBottom: 6 }}>{t}</div>
      <p style={{ color: 'var(--grey-600)', fontSize: 13.5, margin: 0, lineHeight: 1.5 }}>{d}</p>
    </div>
  );
}

/* ---------- FAQ ---------- */
const FAQS = [
  {
    q: 'Which receipts qualify?',
    a: 'Any single SunFront purchase of MVR 1,000 or above. Bills under MVR 1,000 do not qualify. Receipts cannot be combined.',
  },
  {
    q: 'How many predictions do I get per bill?',
    a: 'One prediction per MVR 1,000 spent. A bill of MVR 3,000 gives you 3 predictions across any matches you choose.',
  },
  {
    q: 'Can I predict the same match with multiple bills?',
    a: 'Yes. If you have two qualifying bills, you can predict the same match twice -- one entry per bill.',
  },
  {
    q: 'When does a prediction close?',
    a: 'Exactly at kickoff. Once the match starts, your pick is locked. Submit before the whistle.',
  },
  {
    q: 'How do I win a prize?',
    a: 'Each correct prediction earns one draw entry. At the end of the campaign, winners are drawn and contacted on the mobile number you provided.',
  },
  {
    q: 'What if I win -- how do I claim?',
    a: 'We contact you on the mobile number from your original bill. You must present the physical bill or a clear photo of it to claim.',
  },
  {
    q: 'Can I change my prediction after submitting?',
    a: 'Yes, as long as the match has not started. Once kickoff happens, your pick is final.',
  },
];

function FAQSection() {
  const [open, setOpen] = React.useState(null);
  return (
    <section style={{ background: '#fff', padding: '64px 0 56px' }}>
      <div style={{ maxWidth: 860, margin: '0 auto', padding: '0 clamp(16px,4vw,28px)' }}>
        <Eyebrow>FAQ</Eyebrow>
        <h2 className="font-display" style={{ fontSize: 'clamp(26px,5vw,42px)', lineHeight: 1, margin: '12px 0 36px', letterSpacing: '-0.02em' }}>
          Quick answers.
        </h2>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
          {FAQS.map(function(f, i) {
            const isOpen = open === i;
            const isLast = i === FAQS.length - 1;
            return (
              <div key={i} style={{
                borderTop: '1px solid var(--grey-200)',
                borderBottom: isLast ? '1px solid var(--grey-200)' : 'none',
              }}>
                <button
                  onClick={function() { setOpen(isOpen ? null : i); }}
                  aria-expanded={isOpen}
                  style={{
                    width: '100%', background: 'none', border: 'none', cursor: 'pointer',
                    display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16,
                    padding: '18px 0', textAlign: 'left',
                  }}>
                  <span className="font-subheading" style={{
                    fontSize: 15, color: 'var(--ink)', fontWeight: 700, flex: 1,
                  }}>{f.q}</span>
                  <span style={{
                    flexShrink: 0, width: 24, height: 24, borderRadius: '50%',
                    background: isOpen ? 'var(--orange)' : 'var(--grey-100)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    transition: 'background 0.15s, transform 0.2s',
                    transform: isOpen ? 'rotate(45deg)' : 'rotate(0deg)',
                  }}>
                    <svg width="10" height="10" viewBox="0 0 10 10" fill="none" aria-hidden="true">
                      <path d="M5 1v8M1 5h8" stroke={isOpen ? '#fff' : 'var(--grey-500)'} strokeWidth="1.8" strokeLinecap="round"/>
                    </svg>
                  </span>
                </button>
                {isOpen && (
                  <div style={{
                    paddingBottom: 18, paddingRight: 40,
                    fontSize: 14.5, color: 'var(--grey-600)', lineHeight: 1.65,
                  }}>
                    {f.a}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

/* ---------- Rules ---------- */
const RULES = [
  'Pick locks at kickoff. Submit before the whistle -- no changes after.',
  'One bill, one pick per match. Got more receipts? More picks.',
  'Name + mobile required. We contact you if you win.',
  'Your details stay private. Stats are totals only -- never personal.',
];

function Rules() {
  return (
    <section style={{ background: 'var(--grey-50)', padding: '64px 0' }}>
      <div style={{ maxWidth: 1200, margin: '0 auto', padding: '0 22px' }}>
        <Eyebrow>The rules</Eyebrow>
        <h2 className="font-display" style={{ fontSize: 'clamp(28px, 5vw, 46px)', lineHeight: 1, margin: '12px 0 28px', letterSpacing: '-0.02em' }}>
          Simple. Fair. Transparent.
        </h2>
        <div className="rules-grid" style={{
          display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 16,
        }}>
          {RULES.map((r, i) => <RuleCard key={i} i={i + 1} text={r} />)}
        </div>
      </div>
    </section>
  );
}

function RuleCard({ i, text }) {
  return (
    <div style={{
      background: '#fff',
      border: '1px solid var(--grey-200)',
      borderRadius: 10,
      padding: '20px 22px',
      display: 'flex', alignItems: 'flex-start', gap: 16,
      boxShadow: '0 2px 10px rgba(17,6,24,0.06)',
    }}>
      <div className="clip-paral font-display" style={{
        width: 60, height: 52, background: 'var(--orange)', color: '#fff',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 20, flexShrink: 0,
      }}>
        {String(i).padStart(2, '0')}
      </div>
      <p style={{ margin: 0, color: 'var(--grey-700)', fontSize: 14.5, lineHeight: 1.55 }}>{text}</p>
    </div>
  );
}

/* ---------- Big bottom CTA ---------- */
function BigCTA({ onCTA }) {
  return (
    <section style={{ background: '#fff', padding: '40px 0 80px' }}>
      <div style={{ maxWidth: 1200, margin: '0 auto', padding: '0 22px' }}>
        <div style={{
          position: 'relative', background: 'var(--orange)', color: '#fff',
          padding: '44px 28px', overflow: 'hidden',
          borderRadius: 12,
          boxShadow: '0 8px 32px rgba(17,6,24,0.12)',
        }}>
          <div className="dot-grid" aria-hidden="true" style={{
            position: 'absolute', inset: 0, opacity: 0.18, pointerEvents: 'none',
          }} />
          <div style={{ position: 'relative', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 22 }}>
            <div style={{ maxWidth: 600 }}>
              <div style={{ fontSize: 11, letterSpacing: '0.2em', textTransform: 'uppercase', fontWeight: 700, opacity: 0.9 }}>
                Got a SunFront receipt?
              </div>
              <div className="font-display" style={{ fontSize: 'clamp(26px, 5vw, 40px)', lineHeight: 1, marginTop: 8, letterSpacing: '-0.02em' }}>
                Make it count. Place your prediction.
              </div>
            </div>
            <button onClick={() => onCTA('predict')} className="font-display btn-press-ink" style={{
              background: 'var(--ink)', color: '#fff', border: 'none',
              borderRadius: 6,
              padding: '18px 26px', fontSize: 15, letterSpacing: '0.06em', textTransform: 'uppercase',
              boxShadow: '0 4px 16px rgba(17,6,24,0.28)',
              display: 'inline-flex', alignItems: 'center', gap: 10,
            }}>
              Predict now <Icon name="arrow" size={18} />
            </button>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- Banner strip ---------- */
function BannerStrip() {
  return (
    <div style={{ position: 'relative', overflow: 'hidden', lineHeight: 0 }}>
      <img
        src="/assets/images/banner-v2.png"
        alt=""
        aria-hidden="true"
        style={{ width: '100%', display: 'block', objectFit: 'cover', maxHeight: 320 }}
      />
      {/* Dark vignette + campaign logo centred on white pill */}
      <div style={{
        position: 'absolute', inset: 0,
        background: 'linear-gradient(to right, rgba(17,6,24,0.60) 0%, rgba(17,6,24,0.28) 40%, rgba(17,6,24,0.28) 60%, rgba(17,6,24,0.60) 100%)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <div className="banner-logo-pill" style={{
          background: 'rgba(255,255,255,0.97)',
          borderRadius: 14, padding: '14px 40px',
          boxShadow: '0 8px 36px rgba(0,0,0,0.50)',
          lineHeight: 0,
        }}>
          <img
            src="/assets/images/wc-logo-v3.png"
            alt="SunFront World Cup Foari 2026"
            style={{ height: 84, width: 'auto', display: 'block' }}
          />
        </div>
      </div>
    </div>
  );
}

/* ---------- Campaign banner below nav ---------- */
function CampaignBannerTop() {
  return (
    <div style={{ lineHeight: 0, overflow: 'hidden' }}>
      <img
        src="/assets/images/web-banner-top.png"
        alt="SunFront × FIFA World Cup 2026 Campaign"
        style={{ width: '100%', display: 'block', objectFit: 'cover', maxHeight: 350 }}
      />
    </div>
  );
}

/* ---------- Campaign banner (prize/promo -- integrated, clickable) ---------- */
function CampaignBanner({ src, alt, onClick, bg, className }) {
  return (
    <section className={className} style={{ background: bg || '#fff', padding: 'clamp(20px,4vw,36px) 0' }}>
      <div style={{ maxWidth: 1200, margin: '0 auto', padding: '0 clamp(16px,4vw,22px)' }}>
        <img
          src={src}
          alt={alt}
          onClick={onClick}
          style={{
            width: '100%', display: 'block', borderRadius: 12,
            boxShadow: '0 8px 32px rgba(17,6,24,0.14)',
            cursor: onClick ? 'pointer' : 'default',
          }}
        />
      </div>
    </section>
  );
}

/* ---------- Advertising banner pool (rotates randomly, never repeats back-to-back) ---------- */
var SPONSOR_ADS = [
  '/assets/images/dkaa-banner.png', '/assets/images/dkaa-fridge-banner.png', '/assets/images/dkaa-washing-machine-banner.png',
  '/assets/images/jbl-banner.png', '/assets/images/samsung-banner.png',
  '/assets/images/kdk-banner.png', '/assets/images/kdk-fan-banner.png',
  '/assets/images/hatari-banner.png', '/assets/images/makute-banner.png', '/assets/images/truemark-banner.png',
];
var _adQueue = [];
var _adLast = null;
function _refillAdQueue() {
  var a = SPONSOR_ADS.slice();
  for (var i = a.length - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)); var t = a[i]; a[i] = a[j]; a[j] = t; }
  // Never let the new batch start with the last-served ad (no back-to-back repeat across refills)
  if (_adLast && a.length > 1 && a[0] === _adLast) { var s = a[0]; a[0] = a[1]; a[1] = s; }
  _adQueue = a;
}
/* Returns the next ad in a shuffled rotation -- distinct within a batch, no adjacent repeats */
function pickSponsorAd() {
  if (_adQueue.length === 0) _refillAdQueue();
  var v = _adQueue.shift();
  _adLast = v;
  return v;
}

/* ---------- Mobile advertising banner pool (390x80, mobile view only) ---------- */
var MOBILE_SPONSOR_ADS = [
  '/assets/images/aima-banner-mobile.png', '/assets/images/aodi-banner-mobile.png',
  '/assets/images/dkaa-ac-banner-mobile.png', '/assets/images/dkaa-washing-machine-banner-mobile.png', '/assets/images/dkaa-fridge-banner-mobile.png',
  '/assets/images/jbl-banner-mobile.png', '/assets/images/samsung-tv-banner-mobile.png',
  '/assets/images/kdk-fan-banner-mobile.png', '/assets/images/kdk-water-heater-banner-mobile.png',
  '/assets/images/hatari-banner-mobile.png', '/assets/images/makute-banner-mobile.png', '/assets/images/truemark-banner-mobile.png',
  '/assets/images/royalbaby-banner-mobile.png', '/assets/images/crompton-banner-mobile.png',
];
var _mobileAdQueue = [];
var _mobileAdLast = null;
function _refillMobileAdQueue() {
  var a = MOBILE_SPONSOR_ADS.slice();
  for (var i = a.length - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)); var t = a[i]; a[i] = a[j]; a[j] = t; }
  if (_mobileAdLast && a.length > 1 && a[0] === _mobileAdLast) { var s = a[0]; a[0] = a[1]; a[1] = s; }
  _mobileAdQueue = a;
}
/* Returns the next mobile ad in a shuffled rotation -- distinct within a batch, no adjacent repeats */
function pickMobileSponsorAd() {
  if (_mobileAdQueue.length === 0) _refillMobileAdQueue();
  var v = _mobileAdQueue.shift();
  _mobileAdLast = v;
  return v;
}

/* ---------- Advertising banner click-through links (per sponsor brand page) ---------- */
var AD_LINKS = {
  '/assets/images/dkaa-banner.png': 'https://webseytu.com/shop/?filter_brand=dkaa&query_type_brand=or',
  '/assets/images/dkaa-ac-banner-mobile.png': 'https://webseytu.com/shop/?filter_brand=dkaa&query_type_brand=or',
  '/assets/images/dkaa-fridge-banner.png': 'https://webseytu.com/shop/?filter_brand=dkaa&query_type_brand=or',
  '/assets/images/dkaa-fridge-banner-mobile.png': 'https://webseytu.com/shop/?filter_brand=dkaa&query_type_brand=or',
  '/assets/images/dkaa-washing-machine-banner.png': 'https://webseytu.com/shop/?filter_brand=dkaa&query_type_brand=or',
  '/assets/images/dkaa-washing-machine-banner-mobile.png': 'https://webseytu.com/shop/?filter_brand=dkaa&query_type_brand=or',
  '/assets/images/jbl-banner.png': 'https://webseytu.com/product-category/special-offers/worldcup-foari/',
  '/assets/images/jbl-banner-mobile.png': 'https://webseytu.com/product-category/special-offers/worldcup-foari/',
  '/assets/images/samsung-banner.png': 'https://webseytu.com/product-category/special-offers/worldcup-foari/',
  '/assets/images/samsung-tv-banner-mobile.png': 'https://webseytu.com/product-category/special-offers/worldcup-foari/',
  '/assets/images/kdk-banner.png': 'https://webseytu.com/shop/?filter_brand=kdk&query_type_brand=or',
  '/assets/images/kdk-water-heater-banner-mobile.png': 'https://webseytu.com/shop/?filter_brand=kdk&query_type_brand=or',
  '/assets/images/kdk-fan-banner.png': 'https://webseytu.com/shop/?filter_brand=kdk&query_type_brand=or',
  '/assets/images/kdk-fan-banner-mobile.png': 'https://webseytu.com/shop/?filter_brand=kdk&query_type_brand=or',
  '/assets/images/hatari-banner.png': 'https://webseytu.com/shop/?filter_brand=hatari&query_type_brand=or',
  '/assets/images/hatari-banner-mobile.png': 'https://webseytu.com/shop/?filter_brand=hatari&query_type_brand=or',
  '/assets/images/makute-banner.png': 'https://webseytu.com/product-category/special-offers/worldcup-foari/',
  '/assets/images/makute-banner-mobile.png': 'https://webseytu.com/product-category/special-offers/worldcup-foari/',
  '/assets/images/truemark-banner.png': 'https://webseytu.com/shop/?filter_brand=truemark&query_type_brand=or',
  '/assets/images/truemark-banner-mobile.png': 'https://webseytu.com/shop/?filter_brand=truemark&query_type_brand=or',
  '/assets/images/aima-banner-mobile.png': 'https://webseytu.com/product-category/special-offers/worldcup-foari/',
  '/assets/images/aodi-banner-mobile.png': 'https://webseytu.com/shop/?filter_brand=aodi&query_type_brand=or',
  '/assets/images/royalbaby-banner-mobile.png': 'https://webseytu.com/shop/?filter_brand=royal-baby&query_type_brand=or',
  '/assets/images/crompton-banner-mobile.png': 'https://webseytu.com/shop/?filter_brand=crompton&query_type_brand=or',
};
/* Returns the brand page URL for an ad banner, or null if none assigned yet */
function getAdLink(src) {
  return AD_LINKS[src] || null;
}

/* ---------- Ad performance tracking (impressions on view, clicks on click) ---------- */
function trackAdEvent(banner, device, eventType) {
  if (!banner) return;
  try {
    fetch('/api/track-ad', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ banner: banner, device: device, event: eventType }),
      keepalive: true,
    }).catch(function() {});
  } catch (e) {}
}

/* Wraps an ad <img> -- fires an impression when >=50% visible, and a click event
   on click. Optionally wraps the image in a click-through link. */
function AdBanner({ src, device, className, style, alt, href, onImgClick }) {
  var ref = React.useRef(null);
  var fired = React.useRef(false);

  React.useEffect(function() {
    if (!src || !ref.current || typeof IntersectionObserver === 'undefined') return;
    var el = ref.current;
    var obs = new IntersectionObserver(function(entries) {
      entries.forEach(function(entry) {
        if (entry.isIntersecting && !fired.current) {
          fired.current = true;
          trackAdEvent(src, device, 'impression');
          obs.disconnect();
        }
      });
    }, { threshold: 0.5 });
    obs.observe(el);
    return function() { obs.disconnect(); };
  }, [src, device]);

  var img = (
    <img
      ref={ref}
      src={src}
      alt={alt || ''}
      loading="lazy"
      className={className}
      style={(href || onImgClick) ? Object.assign({}, style, { cursor: 'pointer' }) : style}
      onClick={!href ? function(e) { trackAdEvent(src, device, 'click'); if (onImgClick) onImgClick(e); } : undefined}
    />
  );
  if (href) {
    return (
      <a href={href} target="_blank" rel="noopener noreferrer" style={{ display: 'contents' }}
        onClick={function() { trackAdEvent(src, device, 'click'); }}>
        {img}
      </a>
    );
  }
  return img;
}

/* ---------- Sponsor strip (partner ad -- rotates, no back-to-back repeat) ---------- */
function SponsorStrip({ src, alt, mobileSrc }) {
  var chosen = React.useState(function() { return src || pickSponsorAd(); })[0];
  var chosenMobile = React.useState(function() { return mobileSrc || pickMobileSponsorAd(); })[0];
  var imgStyle = {
    width: '100%', borderRadius: 10,
    border: '1px solid var(--grey-200)',
    boxShadow: '0 2px 12px rgba(17,6,24,0.06)',
  };
  var linkDesktop = getAdLink(chosen);
  var linkMobile = getAdLink(chosenMobile);
  return (
    <section style={{ background: 'var(--grey-50)', padding: 'clamp(22px,4vw,38px) 0' }}>
      <div style={{ maxWidth: 1100, margin: '0 auto', padding: '0 clamp(16px,4vw,22px)' }}>
        <AdBanner src={chosen} device="desktop" alt={alt || 'Campaign partner'}
          className="sponsor-desktop-banner" style={imgStyle} href={linkDesktop} />
        <AdBanner src={chosenMobile} device="mobile" alt={alt || 'Campaign partner'}
          className="sponsor-mobile-banner" style={imgStyle} href={linkMobile} />
      </div>
    </section>
  );
}

/* ---------- Compose page ---------- */
function HomePage({ onNav }) {
  return (
    <main>
      <HomeHero onCTA={onNav} />

      {/* Mobile-only sub-hero banner -- 390x80, full width, auto height */}
      <img
        src="/assets/images/mobile-sub-banner.gif"
        alt="SunFront World Cup Foari 2026"
        className="mobile-sub-banner"
        style={{ width: '100%', height: 'auto' }}
      />

      {/* Grand prize teaser -- right after hero, clickable to predict */}
      <CampaignBanner
        className="product-banner-section"
        src="/assets/images/product-banner.png"
        alt="Grand Prize MVR 50,000 SunFront Gift Voucher + 39 Matchday Winners"
        onClick={() => onNav('predict')}
      />

      <NextUpSpotlight onCTA={onNav} />

      <PrizesSection />

      <FullScheduleSection onCTA={onNav} />

      {/* Sponsor -- random rotation */}
      <SponsorStrip />

      <HowItWorks />
      <Rules />

      {/* Sponsor -- random rotation */}
      <SponsorStrip />

      <FAQSection />
      <BigCTA onCTA={onNav} />
    </main>
  );
}

Object.assign(window, { HomePage, CampaignBanner, SponsorStrip, SPONSOR_ADS, pickSponsorAd, MOBILE_SPONSOR_ADS, pickMobileSponsorAd, getAdLink, trackAdEvent, AdBanner });
