/* ============================================================
   Puntarenas FC — Shared React components
   All components exported to window for cross-file use.
   ============================================================ */

const { useState, useEffect, useMemo, useRef, createContext, useContext } = React;

// ---------- i18n + theme context ----------
const AppCtx = createContext({ lang: 'es', t: {}, theme: 'light', accent: 'orange', setLang: () => {}, setTheme: () => {}, setAccent: () => {} });

function AppProvider({ children }) {
  const [lang, setLang]   = useState(() => localStorage.getItem('pfc_lang')  || 'es');
  const [theme, setTheme] = useState(() => localStorage.getItem('pfc_theme') || 'light');
  const [accent, setAccent] = useState(() => localStorage.getItem('pfc_accent') || 'orange');

  useEffect(() => {
    document.documentElement.setAttribute('data-theme', theme);
    localStorage.setItem('pfc_theme', theme);
  }, [theme]);
  useEffect(() => {
    localStorage.setItem('pfc_lang', lang);
    document.documentElement.lang = lang;
  }, [lang]);
  useEffect(() => {
    const map = {
      orange: { accent: '#F37021', hot: '#FF5A0A' },
      ocean:  { accent: '#1F6A9C', hot: '#2A7FBA' },
      sunset: { accent: '#E14B2A', hot: '#FF6B3D' },
    };
    const c = map[accent] || map.orange;
    document.documentElement.style.setProperty('--accent', c.accent);
    document.documentElement.style.setProperty('--accent-hot', c.hot);
    localStorage.setItem('pfc_accent', accent);
  }, [accent]);

  const t = (window.PFC_I18N || {})[lang] || {};
  return (
    <AppCtx.Provider value={{ lang, t, theme, accent, setLang, setTheme, setAccent }}>
      {children}
    </AppCtx.Provider>
  );
}
const useApp = () => useContext(AppCtx);

// ---------- Icon helpers ----------
const Icon = ({ name, size = 18, ...p }) => {
  const paths = {
    sun:    <><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/></>,
    moon:   <path d="M20 14.5A8 8 0 1 1 9.5 4a6.5 6.5 0 0 0 10.5 10.5z"/>,
    arrow:  <path d="M5 12h14M13 6l6 6-6 6"/>,
    cal:    <><rect x="3" y="4" width="18" height="18" rx="2"/><path d="M16 2v4M8 2v4M3 10h18"/></>,
    pin:    <><path d="M12 22s-7-7.5-7-13a7 7 0 1 1 14 0c0 5.5-7 13-7 13z"/><circle cx="12" cy="9" r="2.5"/></>,
    tv:     <><rect x="2" y="5" width="20" height="14" rx="2"/><path d="M8 21h8"/></>,
    search: <><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></>,
    bell:   <><path d="M18 16v-5a6 6 0 0 0-12 0v5l-2 2h16z"/><path d="M10 21a2 2 0 0 0 4 0"/></>,
    ig:     <><rect x="3" y="3" width="18" height="18" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.5" cy="6.5" r="1" fill="currentColor"/></>,
    x:      <path d="M4 4l16 16M20 4 4 20"/>,
    fb:     <path d="M14 9h3V6h-3a4 4 0 0 0-4 4v2H7v3h3v6h3v-6h3l1-3h-4v-2a1 1 0 0 1 1-1z"/>,
    yt:     <><path d="M2 12c0-3 .3-5 .5-5.8C2.8 5.2 4 4.5 5.2 4.4 7.4 4.2 12 4 12 4s4.6.2 6.8.4c1.2.1 2.4.8 2.7 1.8.2.8.5 2.8.5 5.8s-.3 5-.5 5.8c-.3 1-1.5 1.7-2.7 1.8-2.2.2-6.8.4-6.8.4s-4.6-.2-6.8-.4C4 19.5 2.8 18.8 2.5 17.8 2.3 17 2 15 2 12z"/><path d="m10 9 6 3-6 3z" fill="currentColor"/></>,
    tiktok: <path d="M14 4v9.5a3 3 0 1 1-3-3M14 4c0 2.5 2 4 4.5 4V11C17 11 15.5 10.5 14 9.5"/>,
    edit:   <><path d="m12 20 9-9-3-3-9 9v3z"/><path d="M15 8l3 3"/></>,
    trash:  <><path d="M4 7h16M10 11v6M14 11v6"/><path d="M6 7v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V7"/><path d="M9 7V4h6v3"/></>,
    plus:   <><path d="M12 5v14M5 12h14"/></>,
    check:  <path d="m5 12 5 5 9-11"/>,
    close:  <path d="M6 6l12 12M18 6 6 18"/>,
    menu:   <><path d="M4 7h16M4 12h16M4 17h16"/></>,
    ticket: <><path d="M4 9a2 2 0 0 0 0 6v3h16v-3a2 2 0 0 0 0-6V6H4z"/><path d="M13 6v12"/></>,
    shop:   <><path d="M4 7h16l-1 12H5z"/><path d="M9 7a3 3 0 0 1 6 0"/></>,
    shield: <><path d="M12 3 4 6v6c0 5 3.5 8.5 8 9 4.5-.5 8-4 8-9V6z"/></>,
    dashboard: <><rect x="3" y="3" width="7" height="9"/><rect x="14" y="3" width="7" height="5"/><rect x="14" y="12" width="7" height="9"/><rect x="3" y="16" width="7" height="5"/></>,
    users:  <><circle cx="9" cy="8" r="4"/><path d="M2 21a7 7 0 0 1 14 0"/><circle cx="17" cy="7" r="3"/><path d="M22 19a5 5 0 0 0-5-5"/></>,
    news:   <><rect x="3" y="4" width="18" height="16" rx="2"/><path d="M7 8h10M7 12h10M7 16h6"/></>,
    whistle:<><circle cx="9" cy="14" r="6"/><path d="M14.5 11 22 8M14.5 13l4 2"/></>,
    settings:<><circle cx="12" cy="12" r="3"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/></>,
    image:  <><rect x="3" y="4" width="18" height="16" rx="2"/><circle cx="9" cy="10" r="2"/><path d="m4 19 5-5 4 4 2-2 5 5"/></>,
    chart:  <><path d="M3 20h18M6 16V9M11 16V5M16 16v-7M21 16v-3"/></>,
  };
  return (
    <svg viewBox="0 0 24 24" width={size} height={size} fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" {...p}>
      {paths[name] || null}
    </svg>
  );
};

// ---------- Shark-pattern thumb (news media placeholder) ----------
function SharkThumb({ hue = 18, children }) {
  const h1 = `hsl(${hue} 75% 52%)`;
  const h2 = `hsl(${(hue + 18) % 360} 62% 32%)`;
  const h3 = `hsl(${(hue + 200) % 360} 55% 18%)`;
  return (
    <div className="shark-thumb" style={{ '--t1': h1, '--t2': h2, '--t3': h3 }}>
      <div className="shark-thumb__badge">{children}</div>
      {/* stylized shark silhouette */}
      <svg viewBox="0 0 400 240" style={{position:'absolute', right:-24, bottom:10, width:'72%', height:'auto', opacity:0.22}}>
        <path fill="#000" d="M40 150c60-40 130-55 210-45 20 3 36 10 48 20l40-6-22 20 26 18-44-2c-14 12-34 22-60 28-90 20-172 2-208-20l-18 10 8-20-12-20 32 17z"/>
        <circle cx="260" cy="130" r="4" fill="#fff"/>
      </svg>
    </div>
  );
}

// ---------- Top ticker ----------
function Ticker() {
  const { t } = useApp();
  const items = [
    { type: 'result', comp: 'J16', txt: 'HER 1 — 2 PFC', cls: 'won' },
    { type: 'next',   txt: 'PFC vs Saprissa · Sáb 2 May · 19:00' },
    { type: 'result', comp: 'J15', txt: 'PFC 3 — 0 PZ', cls: 'won' },
    { type: 'text',   txt: '#VamosMarea' },
    { type: 'result', comp: 'J14', txt: 'LDA 2 — 2 PFC', cls: 'drew' },
    { type: 'text',   txt: 'Abonos Clausura disponibles' },
    { type: 'result', comp: 'J13', txt: 'PFC 0 — 1 CAR', cls: 'lost' },
    { type: 'text',   txt: '4º en la tabla · 28 pts' },
  ];
  const row = [...items, ...items];
  return (
    <div className="ticker">
      <div className="ticker-track">
        {row.map((it, i) => (
          <span key={i} className="ticker-item">
            <span className="dot"/>
            {it.type === 'result' && <>
              <span style={{color:'#7A828C'}}>{it.comp}</span>
              <span className={`score ${it.cls}`}>{it.txt}</span>
            </>}
            {it.type !== 'result' && <span>{it.txt}</span>}
          </span>
        ))}
      </div>
    </div>
  );
}

// ---------- Main nav ----------
function Nav({ active = 'home' }) {
  const { t, lang, setLang, theme, setTheme } = useApp();
  const [open, setOpen] = useState(false);
  const links = [
    { id: 'home',      label: t.nav?.home,      href: 'home.html' },
    { id: 'fixtures',  label: t.nav?.fixtures,  href: 'fixtures.html' },
    { id: 'standings', label: t.nav?.standings, href: 'standings.html' },
    { id: 'squad',     label: t.nav?.squad,     href: 'squad.html' },
    { id: 'news',      label: t.nav?.news,      href: 'news.html' },
    { id: 'about',     label: t.nav?.about,     href: 'about.html' },
  ];
  useEffect(() => {
    document.body.style.overflow = open ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [open]);
  return (
    <nav className="nav">
      <div className="nav-inner">
        <a href="home.html" className="nav-brand">
          <img src="assets/pfc-logo.png" alt="Puntarenas FC"/>
          <span className="nav-brand-text">
            Puntarenas FC
            <small>Tiburones del Puerto</small>
          </span>
        </a>
        <div className="nav-links">
          {links.map(l => (
            <a key={l.id} href={l.href} className={`nav-link ${active === l.id ? 'active' : ''}`}>{l.label}</a>
          ))}
        </div>
        <div className="nav-right">
          <a href="#tickets" className="btn btn-primary btn-sm nav-ticket-btn">
            <Icon name="ticket" size={16}/> <span className="ticket-label">{t.nav?.tickets}</span>
          </a>
          <div className="lang-switch">
            <button className={lang === 'es' ? 'on' : ''} onClick={() => setLang('es')}>ES</button>
            <button className={lang === 'en' ? 'on' : ''} onClick={() => setLang('en')}>EN</button>
          </div>
          <button className="theme-toggle" onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')} aria-label="Toggle theme">
            <Icon name={theme === 'light' ? 'moon' : 'sun'} size={16}/>
          </button>
          <a href="admin.html" className="btn btn-ghost btn-sm nav-admin-btn" title="Admin panel">
            <Icon name="shield" size={14}/> <span className="admin-label">{t.nav?.admin}</span>
          </a>
          <button className="nav-burger" aria-label="Menu" onClick={() => setOpen(true)}>
            <Icon name="menu" size={22}/>
          </button>
        </div>
      </div>

      {open && (
        <div className="mobile-drawer" onClick={() => setOpen(false)}>
          <div className="mobile-drawer__panel" onClick={e => e.stopPropagation()}>
            <div className="mobile-drawer__head">
              <a href="home.html" className="nav-brand">
                <img src="assets/pfc-logo.png" alt=""/>
                <span className="nav-brand-text">Puntarenas FC<small>Tiburones del Puerto</small></span>
              </a>
              <button className="theme-toggle" aria-label="Close" onClick={() => setOpen(false)}>
                <Icon name="close" size={18}/>
              </button>
            </div>
            <div className="mobile-drawer__links">
              {links.map(l => (
                <a key={l.id} href={l.href} className={`mobile-link ${active === l.id ? 'active' : ''}`}>
                  {l.label}
                  <Icon name="arrow" size={16}/>
                </a>
              ))}
            </div>
            <div className="mobile-drawer__foot">
              <a href="#tickets" className="btn btn-primary" style={{width:'100%'}}>
                <Icon name="ticket" size={16}/> {t.nav?.tickets}
              </a>
              <a href="admin.html" className="btn btn-ghost" style={{width:'100%'}}>
                <Icon name="shield" size={14}/> {t.nav?.admin}
              </a>
              <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', gap:10}}>
                <div className="lang-switch">
                  <button className={lang === 'es' ? 'on' : ''} onClick={() => setLang('es')}>ES</button>
                  <button className={lang === 'en' ? 'on' : ''} onClick={() => setLang('en')}>EN</button>
                </div>
                <button className="theme-toggle" onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')} aria-label="Toggle theme">
                  <Icon name={theme === 'light' ? 'moon' : 'sun'} size={16}/>
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </nav>
  );
}

// ---------- Footer ----------
function Footer() {
  const { t } = useApp();
  const D = window.PFC_DATA;
  return (
    <footer className="footer">
      <div className="container-wide">
        <div className="sponsors-strip">
          {D.sponsors.map(s => <span key={s} className="sponsor-chip">{s}</span>)}
        </div>
        <div className="footer-grid">
          <div>
            <div className="footer-brand-row">
              <img src="assets/pfc-logo.png" alt=""/>
              <div>
                <div className="footer-tagline">{t.footer?.tagline}</div>
                <div className="footer-sub">Fundado en {D.club.founded} · {D.club.stadium}</div>
              </div>
            </div>
            <p style={{color:'#A8AEB6', fontSize:14, maxWidth:420}}>
              Puntarenas Fútbol Club · Orgullo del Puerto · {D.club.city}.
            </p>
            <div className="social-row" style={{marginTop:16}}>
              <a className="social-btn" href="#" aria-label="Instagram"><Icon name="ig" size={16}/></a>
              <a className="social-btn" href="#" aria-label="X"><Icon name="x" size={16}/></a>
              <a className="social-btn" href="#" aria-label="Facebook"><Icon name="fb" size={16}/></a>
              <a className="social-btn" href="#" aria-label="YouTube"><Icon name="yt" size={16}/></a>
              <a className="social-btn" href="#" aria-label="TikTok"><Icon name="tiktok" size={16}/></a>
            </div>
          </div>
          <div>
            <h4>{t.footer?.club}</h4>
            <ul>
              <li><a href="about.html">{t.nav?.about}</a></li>
              <li><a href="squad.html">{t.nav?.squad}</a></li>
              <li><a href="#stadium">{D.club.stadium}</a></li>
              <li><a href="#academy">Cantera · U-17 / U-20</a></li>
            </ul>
          </div>
          <div>
            <h4>{t.footer?.info}</h4>
            <ul>
              <li><a href="fixtures.html">{t.nav?.fixtures}</a></li>
              <li><a href="standings.html">{t.nav?.standings}</a></li>
              <li><a href="news.html">{t.nav?.news}</a></li>
              <li><a href="#tickets">{t.nav?.tickets}</a></li>
              <li><a href="#shop">{t.nav?.shop}</a></li>
            </ul>
          </div>
          <div>
            <h4>{t.footer?.follow}</h4>
            <ul>
              <li><a href="#">IG {D.social.instagram}</a></li>
              <li><a href="#">X {D.social.x}</a></li>
              <li><a href="#">FB {D.social.facebook}</a></li>
              <li><a href="#">YT {D.social.youtube}</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© {new Date().getFullYear()} Puntarenas FC · {t.footer?.rights}</span>
          <span>{D.club.stadium} · {D.club.city}</span>
        </div>
      </div>
    </footer>
  );
}

// ---------- Crest dot (used in match cards) ----------
function Crest({ code, color }) {
  return (
    <div className="match-crest" style={{ background: color || '#333' }}>
      {code}
    </div>
  );
}

// ---------- Match card ----------
function MatchCard({ m, kind = 'fixture' }) {
  const { lang } = useApp();
  const isResult = kind === 'result';
  const date = new Date(m.date + (m.time ? `T${m.time}:00-06:00` : 'T12:00:00-06:00'));
  const dateLabel = date.toLocaleDateString(lang === 'es' ? 'es-CR' : 'en-US', { weekday: 'short', day: 'numeric', month: 'short' });
  return (
    <div className="match-card">
      <div className="match-card__head">
        <span>{m.comp || m.competition}</span>
        <span>{dateLabel}{m.time ? ` · ${m.time}` : ''}</span>
      </div>
      <div className="match-card__body">
        <div className="match-team match-team--home">
          <span className="match-team__name">{m.home}</span>
          <Crest code={(m.home || '').slice(0,3).toUpperCase()} color={m.home?.includes('Puntarenas') ? '#F37021' : '#353B43'}/>
        </div>
        {isResult ? (
          <div className="match-score num">
            <span>{m.hs}</span><span className="sep">–</span><span>{m.as}</span>
          </div>
        ) : (
          <div className="match-time num">{m.time || 'TBD'}</div>
        )}
        <div className="match-team match-team--away">
          <Crest code={(m.away || '').slice(0,3).toUpperCase()} color={m.away?.includes('Puntarenas') ? '#F37021' : '#353B43'}/>
          <span className="match-team__name">{m.away}</span>
        </div>
      </div>
      <div className="match-card__head" style={{borderTop:'1px solid var(--line)', borderBottom:'none'}}>
        <span><Icon name="pin" size={12} style={{verticalAlign:'-2px', marginRight:6}}/>{m.venue}</span>
        {isResult
          ? <span className={`match-result-chip chip-${m.result}`}>{m.result}</span>
          : <a className="link-arrow" href="#tickets">Boletos <Icon name="arrow" size={12}/></a>}
      </div>
    </div>
  );
}

// ---------- Countdown (hero) ----------
function Countdown({ to }) {
  const { t } = useApp();
  const [now, setNow] = useState(() => Date.now());
  useEffect(() => {
    const id = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(id);
  }, []);
  const target = new Date(to).getTime();
  let diff = Math.max(0, target - now);
  const d = Math.floor(diff / 86400000); diff %= 86400000;
  const h = Math.floor(diff / 3600000);  diff %= 3600000;
  const mi = Math.floor(diff / 60000);   diff %= 60000;
  const s = Math.floor(diff / 1000);
  const pad = (n) => String(n).padStart(2,'0');
  return (
    <div className="countdown">
      <div className="cd-block"><div className="cd-value num">{pad(d)}</div><div className="cd-label">{t.hero?.countdown?.d}</div></div>
      <div className="cd-block"><div className="cd-value num">{pad(h)}</div><div className="cd-label">{t.hero?.countdown?.h}</div></div>
      <div className="cd-block"><div className="cd-value num">{pad(mi)}</div><div className="cd-label">{t.hero?.countdown?.m}</div></div>
      <div className="cd-block"><div className="cd-value num">{pad(s)}</div><div className="cd-label">{t.hero?.countdown?.s}</div></div>
    </div>
  );
}

// ---------- Page shell ----------
function Page({ active, children }) {
  return (
    <>
      <Ticker/>
      <Nav active={active}/>
      <main>{children}</main>
      <Footer/>
    </>
  );
}

Object.assign(window, {
  AppProvider, useApp, AppCtx,
  Icon, SharkThumb, Ticker, Nav, Footer, Crest,
  MatchCard, Countdown, Page,
});
