// ============================================================================
// pages-home-about.jsx — Home & About
// ============================================================================

// --- Live countdown ---------------------------------------------------------
function Countdown() {
  const [now, setNow] = React.useState(Date.now());
  React.useEffect(() => {
    const t = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(t);
  }, []);
  const diff = Math.max(0, GAMES_DATE.getTime() - now);
  const s = Math.floor(diff / 1000);
  const parts = [
    { v: Math.floor(s / 86400), l: 'DAYS' },
    { v: Math.floor((s % 86400) / 3600), l: 'HRS' },
    { v: Math.floor((s % 3600) / 60), l: 'MIN' },
    { v: s % 60, l: 'SEC' },
  ];
  const pad = (n) => String(n).padStart(2, '0');
  return (
    <div className="countdown">
      {parts.map((p, i) => (
        <React.Fragment key={p.l}>
          <div className="cd">
            <span className="cd__num">{pad(p.v)}</span>
            <span className="cd__lbl">{p.l}</span>
          </div>
          {i < parts.length - 1 && <span className="cd__sep">:</span>}
        </React.Fragment>
      ))}
    </div>
  );
}

function TeamModal({ team, onClose }) {
  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'Escape') onClose();
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);

  const photos = team.statePhotos || [];
  return (
    <div className="teammodal" role="dialog" aria-modal="true" aria-label={`${team.name} contingent details`} onClick={onClose}>
      <div className="teammodal__panel" style={{ '--team': team.color }} onClick={(e) => e.stopPropagation()}>
        <button className="teammodal__close" type="button" onClick={onClose} aria-label="Close team details">×</button>
        <div className="teammodal__hero">
          <span className={`teammodal__crest teamtile__crest--${team.code.toLowerCase()}`}>
            <img src={team.logo} alt={`${team.name} logo`} />
          </span>
          <div>
            <span className="teammodal__eyebrow">Contingent</span>
            <h3>{team.name}</h3>
            <div className="teammodal__tags">
              {team.participation && <span>{team.participation}</span>}
              {team.win && <span>{team.win} Champions</span>}
            </div>
          </div>
        </div>
        <p className="teammodal__desc">{team.stateSummary || team.description}</p>
        {photos.length > 0 ? (
          <div className="teammodal__photos">
            {photos.map((photo, i) => (
            <img key={photo} src={photo} alt={`${team.name} state activity ${i + 1}`} loading="lazy" />
            ))}
          </div>
        ) : (
          <div className="teammodal__empty">State activity photos coming soon.</div>
        )}
      </div>
    </div>
  );
}

// --- Home -------------------------------------------------------------------
function HomePage() {
  const [activeTeam, setActiveTeam] = React.useState(null);
  const [selectedTeam, setSelectedTeam] = React.useState(null);
  return (
    <main>
      <section className="hero">
        <img className="hero__art" src={ASSETS.header} alt="" />
        <div className="hero__scrim" aria-hidden="true" />
        <div className="hero__center">
          <h1 className="hero__title">MUAFAKAT<br />GAMES</h1>
          <Countdown />
        </div>
      </section>

      <div className="wrap">
        <h2 className="shout">JOIN THE ULTIMATE<br />SPORTS EVENT!</h2>
      </div>

      <div className="wrap wrap--wide">
        <Carousel label="event highlight" sources={ASSETS.events} />
      </div>

      <div className="wrap">
        <p className="lede">
          Muafakat Games is an international sports event bringing together athletes
          from around the world. Our mission is to foster unity and sportsmanship
          through competitive sports.
        </p>
      </div>

      <div className="wrap teams">
        <div className="teams__head">
          <span className="teams__eyebrow">Contingents</span>
          <h2 className="teams__title">Participating Teams</h2>
        </div>
        <div className="teams__grid">
          {TEAM_CODES.map((code) => {
            const t = TEAMS[code];
            const hasTeamDetails = Boolean(t.stateSummary || (t.statePhotos && t.statePhotos.length > 0));
            return (
              <button
                key={code}
                type="button"
                className={`teamtile ${activeTeam === code ? 'is-active' : ''}`}
                style={{ '--team': t.color }}
                onClick={() => {
                  if (hasTeamDetails) {
                    setActiveTeam(null);
                    setSelectedTeam(code);
                    return;
                  }
                  setActiveTeam((current) => current === code ? null : code);
                }}
                aria-haspopup={hasTeamDetails ? 'dialog' : undefined}
                aria-expanded={hasTeamDetails ? undefined : activeTeam === code}>
                {t.participation && <span className="teamtile__participation">{t.participation}</span>}
                {t.win && <span className="teamtile__win">{t.win} Champions</span>}
                <span className={`teamtile__crest teamtile__crest--${code.toLowerCase()}`}>
                  <img src={t.logo} alt={`${t.name} logo`} />
                </span>
                <span className="teamtile__name">{t.name}</span>
                <span className="teamtile__info">
                  <span className="teamtile__media">
                    <img src={t.logo} alt="" />
                  </span>
                  <span className="teamtile__info-copy">
                    <b>{t.name}</b>
                    <em>{t.win ? `${t.win} Champions` : t.participation}</em>
                    <span>{t.description}</span>
                  </span>
                </span>
              </button>
            );
          })}
        </div>
      </div>
      {selectedTeam && <TeamModal team={TEAMS[selectedTeam]} onClose={() => setSelectedTeam(null)} />}

      <div className="wrap aboutphotos">
        <Gallery rows={2} cols={3} label="games highlight" sources={ASSETS.events.slice(1)} />
      </div>

      <div className="wrap partners">
        <div className="partner">
          <h4 className="partner__label">Partnered with</h4>
          <img className="partner__logo partner__logo--img" src={ASSETS.logoEma} alt="Education Malaysia Australia" />
          <p className="partner__cap">Education Malaysia Australia (EMA)</p>
        </div>
        <div className="partner">
          <h4 className="partner__label">Supported by</h4>
          <img className="partner__logo partner__logo--img" src={ASSETS.logoConsulate} alt="Consulate General of Malaysia, Melbourne" />
          <p className="partner__cap">Consulate General of Malaysia, Melbourne</p>
        </div>
      </div>
    </main>
  );
}

// --- About ------------------------------------------------------------------
function AboutPage() {
  return (
    <main>
      <div className="wrap about__head">
        <div className="about__intro">
          <h1 className="ghead ghead--green">ABOUT US</h1>
          <p className="about__p">
            The Muafakat Games is an <strong>annual sports event</strong> held by
            Malaysian students in tertiary institutions across Australia, endorsed
            directly by <strong>Education Malaysia Australia (EMA)</strong>.
          </p>
          <p className="about__p">
            The event aims to foster a spirit of teamwork and work towards building a
            sense of unity amongst fellow Malaysians regardless of different
            backgrounds and cultures.
          </p>
        </div>
        <Ph src={ASSETS.duo} fit="contain" label="tiger + koala mascots" className="about__mascots" />
      </div>

      <div className="wrap wrap--wide">
        <Carousel label="celebration" sources={ASSETS.events} />
      </div>

      <div className="wrap">
        <h2 className="centre-title">OUR PILLARS</h2>
        <div className="pillars">
          {PILLARS.map((p) => (
            <div
              key={p.title}
              className={`pillar pillar--${p.tone}`}
              style={{ marginTop: p.offset }}
            >
              <span>{p.title}</span>
            </div>
          ))}
        </div>
      </div>

      <div className="wrap">
        <Gallery rows={2} cols={3} label="games highlight" sources={ASSETS.events.slice(1)} />
      </div>
    </main>
  );
}

Object.assign(window, { HomePage, AboutPage, Countdown });
