// ui-kit.jsx — palette (TED white/black/red), logo, header, footer, shared bits

const C = {
  white: '#ffffff',
  paper: '#f6f4f1',
  paperDeep: '#ece8e2',
  ink: '#0a0a0a',
  ink70: 'rgba(10,10,10,0.70)',
  ink55: 'rgba(10,10,10,0.55)',
  ink40: 'rgba(10,10,10,0.40)',
  red: '#e80028',
  rule: 'rgba(10,10,10,0.14)',
  ruleSoft: 'rgba(10,10,10,0.08)',
};
const FONT = {
  serif: '"Cormorant Garamond", "EB Garamond", Georgia, serif',
  sans: '"Inter Tight", system-ui, sans-serif',
  mono: '"JetBrains Mono", ui-monospace, Menlo, monospace',
};
const MAIL = {
  news: 'news@tedxfaenza.it',
  staff: 'staff@tedxfaenza.it',
  partner: 'partner@tedxfaenza.it',
};
window.C = C; window.FONT = FONT; window.MAIL = MAIL;

// Tally form ids (from config.js). A blank id means "keep the mailto fallback".
const TALLY = (typeof window !== 'undefined' && window.TEDX_CONFIG && window.TEDX_CONFIG.tally) || {};
function tallyId(key) { return (TALLY[key] || '').trim(); }
window.TALLY = TALLY; window.tallyId = tallyId;

// Inline Tally embed. Renders a transparent, auto-resizing iframe and (re)inits
// it on mount so it works across hash-route changes. Falls back to setting the
// iframe src directly if tally.so/widgets/embed.js hasn't loaded yet.
function TallyEmbed({ formId, title = 'Modulo TEDxFaenza', minHeight = 320 }) {
  const ref = React.useRef(null);
  const src = `https://tally.so/embed/${formId}?alignLeft=1&hideTitle=1&transparentBackground=1&dynamicHeight=1`;
  React.useEffect(() => {
    if (typeof window.Tally !== 'undefined') { window.Tally.loadEmbeds(); return; }
    const f = ref.current && ref.current.querySelector('iframe[data-tally-src]');
    if (f && !f.src) f.src = f.dataset.tallySrc;
  }, [formId]);
  return (
    <div ref={ref}>
      <iframe data-tally-src={src} loading="lazy" width="100%" height={minHeight}
        frameBorder="0" marginHeight="0" marginWidth="0" title={title}
        style={{ border: 0, display: 'block', width: '100%' }}/>
    </div>
  );
}
window.TallyEmbed = TallyEmbed;

// Logo — official PNG lockup (black or white version), served from repo root.
function Logo({ variant = 'black', height = 30, style }) {
  const src = variant === 'white' ? 'logo-white.png' : 'logo-black.png';
  return <img src={src} alt="TEDxFaenza" style={{ height, width: 'auto', display: 'block', ...style }}/>;
}
window.Logo = Logo;

// Eyebrow label
function Eyebrow({ children, color = C.red, style }) {
  return (
    <div style={{ fontFamily: FONT.mono, fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase', color, display: 'flex', alignItems: 'center', gap: 14, ...style }}>
      <span style={{ width: 28, height: 1, background: color }}/>
      {children}
    </div>
  );
}
window.Eyebrow = Eyebrow;

// Header — centered logo + split nav on desktop; logo + hamburger drawer on mobile.
// Links are hash routes (`/partner` → `#/partner`); plain `#anchor` entries
// (e.g. Contatti → footer) scroll in-page without changing the route.
function Header({ phase, setPhase, incMetric, route = '/' }) {
  const { isMobile } = useViewport();
  const [open, setOpen] = React.useState(false);

  const left = [['Home', '/'], ['Chi siamo', '/chi-siamo']];
  const right = phase === 'public'
    ? [['Programma', '/speaker'], ['Partner', '/partner'], ['Biglietti', '/biglietti'], ['Contatti', '#contatti']]
    : [['Speaker', '/speaker'], ['Partner', '/partner'], ['Contatti', '#contatti']];
  const allLinks = [...left, ...right];

  const isRoute = (h) => h.startsWith('/');
  const hrefFor = (h) => (isRoute(h) ? '#' + h : h);
  const isActive = (h) => isRoute(h) && route === h;

  // Auto-close the drawer when growing back to desktop, and lock body scroll while open.
  React.useEffect(() => { if (!isMobile && open) setOpen(false); }, [isMobile, open]);
  React.useEffect(() => {
    document.body.style.overflow = open ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [open]);

  const NavLink = ({ l, h }) => {
    const active = isActive(h);
    const inPage = !isRoute(h);
    return (
      <a href={hrefFor(h)} data-cursor className="ulink" aria-current={active ? 'page' : undefined}
        onClick={inPage ? (e) => scrollToId(h.slice(1), e) : undefined}
        onMouseEnter={() => incMetric && incMetric('hovers')}
        style={{ color: active ? C.red : C.ink, textDecoration: 'none', fontFamily: FONT.sans, fontSize: 13, fontWeight: active ? 700 : 500, whiteSpace: 'nowrap' }}>{l}</a>
    );
  };

  if (isMobile) {
    return (
      <>
        <header style={{
          position: 'sticky', top: 0, zIndex: 100,
          background: open ? C.white : `${C.white}f2`, backdropFilter: open ? 'none' : 'blur(10px)',
          borderBottom: `1px solid ${C.rule}`,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '13px 20px' }}>
            <a href="#/" data-cursor data-cursor-label="HOME" onClick={() => setOpen(false)} style={{ textDecoration: 'none', display: 'flex' }}>
              <Logo height={24}/>
            </a>
            <button type="button" aria-label={open ? 'Chiudi menu' : 'Apri menu'} aria-expanded={open}
              data-cursor onClick={() => { setOpen(o => !o); incMetric && incMetric('clicks'); }}
              style={{ position: 'relative', zIndex: 2, width: 40, height: 40, background: 'transparent', border: 'none', cursor: 'pointer', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 6, padding: 0 }}>
              <span style={{ display: 'block', width: 24, height: 2, background: C.ink, transition: 'transform .3s, opacity .3s', transform: open ? 'translateY(8px) rotate(45deg)' : 'none' }}/>
              <span style={{ display: 'block', width: 24, height: 2, background: C.ink, transition: 'opacity .2s', opacity: open ? 0 : 1 }}/>
              <span style={{ display: 'block', width: 24, height: 2, background: C.ink, transition: 'transform .3s, opacity .3s', transform: open ? 'translateY(-8px) rotate(-45deg)' : 'none' }}/>
            </button>
          </div>
        </header>

        {/* Full-screen drawer — sibling of <header> so position:fixed is
            relative to the viewport (the header's backdrop-filter would
            otherwise establish a containing block and clip it). */}
        <div role="dialog" aria-modal="true" aria-hidden={!open} style={{
          position: 'fixed', inset: 0, zIndex: 95,
          background: C.white,
          padding: '84px 24px 40px',
          display: 'flex', flexDirection: 'column',
          transition: 'opacity .35s ease, transform .35s cubic-bezier(.2,.8,.2,1)',
          opacity: open ? 1 : 0,
          transform: open ? 'translateY(0)' : 'translateY(-12px)',
          pointerEvents: open ? 'auto' : 'none',
          overflowY: 'auto',
        }}>
          <div style={{ fontFamily: FONT.mono, fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase', color: C.red, marginBottom: 22 }}>Menu</div>
          <nav style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
            {allLinks.map(([l, h]) => {
              const inPage = !isRoute(h);
              return (
                <a key={l} href={hrefFor(h)} data-cursor tabIndex={open ? 0 : -1} aria-current={isActive(h) ? 'page' : undefined}
                  onClick={(e) => {
                    if (inPage) e.preventDefault();
                    setOpen(false);
                    incMetric && incMetric('clicks');
                    // Wait for the drawer to close + body scroll-lock to lift before jumping.
                    if (inPage) setTimeout(() => scrollToId(h.slice(1)), 380);
                  }}
                  style={{ color: isActive(h) ? C.red : C.ink, textDecoration: 'none', fontFamily: FONT.serif, fontStyle: 'italic', fontSize: 'clamp(30px,9vw,44px)', fontWeight: 500, padding: '10px 0', borderBottom: `1px solid ${C.ruleSoft}` }}>
                  {l}
                </a>
              );
            })}
          </nav>
          <div style={{ marginTop: 'auto', paddingTop: 32, display: 'flex', flexDirection: 'column', gap: 10 }}>
            <div style={{ fontFamily: FONT.mono, fontSize: 10, letterSpacing: '0.16em', textTransform: 'uppercase', color: C.ink40 }}>Scrivici</div>
            <a href={`mailto:${MAIL.partner}`} data-cursor tabIndex={open ? 0 : -1} className="ulink" style={{ fontFamily: FONT.sans, fontSize: 15, fontWeight: 600, color: C.ink, textDecoration: 'none' }}>{MAIL.partner}</a>
          </div>
        </div>
      </>
    );
  }

  return (
    <header style={{
      position: 'sticky', top: 0, zIndex: 100,
      background: `${C.white}f2`, backdropFilter: 'blur(10px)',
      borderBottom: `1px solid ${C.rule}`,
    }}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr auto 1fr', alignItems: 'center', padding: '16px 48px', gap: 24 }}>
        <nav style={{ display: 'flex', gap: 30, justifySelf: 'start' }}>
          {left.map(([l, h]) => <NavLink key={l} l={l} h={h}/>)}
        </nav>
        <a href="#/" data-cursor data-cursor-label="HOME" style={{ justifySelf: 'center', textDecoration: 'none' }}>
          <Logo height={30}/>
        </a>
        <nav style={{ display: 'flex', gap: 30, justifySelf: 'end', alignItems: 'center' }}>
          {right.map(([l, h]) => <NavLink key={l} l={l} h={h}/>)}
        </nav>
      </div>
    </header>
  );
}
window.Header = Header;

// Newsletter band — NOT rendered (removed from the footer per request). Kept as a
// standalone component so it can be re-enabled by dropping <NewsletterBand incMetric={…}/>
// back into the Footer (or anywhere).
function NewsletterBand({ incMetric }) {
  const { isMobile } = useViewport();
  const submitNews = (e) => {
    e.preventDefault();
    incMetric && incMetric('clicks');
    const email = e.target.email.value;
    const tid = tallyId('news');
    if (tid) {
      // Opens the Tally newsletter form with the email prefilled.
      // (Give the Tally email field the key "email" so the prefill lands.)
      window.open(`https://tally.so/r/${tid}?email=${encodeURIComponent(email)}`, '_blank', 'noopener');
      e.target.reset();
      return;
    }
    window.location.href = `mailto:${MAIL.news}?subject=${encodeURIComponent('Iscrizione newsletter · TEDxFaenza')}&body=${encodeURIComponent('Email: ' + email + '\r\nDesidero ricevere gli aggiornamenti di servizio su TEDxFaenza.')}`;
  };
  return (
    <div style={{ borderBottom: '1px solid rgba(255,255,255,0.14)', padding: isMobile ? '48px 20px' : '64px 48px', background: C.ink, color: C.white }}>
      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: isMobile ? 28 : 56, alignItems: 'center', maxWidth: 1280, margin: '0 auto' }}>
        <div>
          <Eyebrow color={C.red} style={{ color: C.red }}>Newsletter · solo info di servizio</Eyebrow>
          <h2 style={{ margin: '18px 0 0', fontFamily: FONT.serif, fontSize: 'clamp(36px,4vw,56px)', lineHeight: 1, fontWeight: 400 }}>
            <em>Niente spam.</em> Solo annunci veri.
          </h2>
          <p style={{ fontFamily: FONT.sans, fontSize: 14, lineHeight: 1.6, marginTop: 18, opacity: 0.7, maxWidth: 460 }}>
            Una mail quando annunciamo gli speaker, una quando apriamo i biglietti. Gli aggiornamenti arrivano da <strong style={{ color: C.white }}>{MAIL.news}</strong>.
          </p>
        </div>
        <form onSubmit={submitNews} style={{ display: 'flex', gap: 0, borderBottom: `1px solid rgba(255,255,255,0.3)` }}>
          <input name="email" type="email" required placeholder="la-tua@email.it"
            style={{ flex: 1, background: 'transparent', border: 'none', outline: 'none', color: C.white, fontFamily: FONT.sans, fontSize: 18, padding: '14px 2px' }}/>
          <Magnetic strength={0.25} onMagnet={() => incMetric && incMetric('magnets')}>
            <button type="submit" data-cursor data-cursor-label="OK"
              style={{ background: C.red, color: C.white, border: 'none', padding: '14px 24px', fontFamily: FONT.sans, fontSize: 13, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase', cursor: 'pointer' }}>
              Iscrivimi →
            </button>
          </Magnetic>
        </form>
      </div>
    </div>
  );
}
window.NewsletterBand = NewsletterBand;

// Footer — contatti + TED license. (Newsletter removed; see NewsletterBand above.)
function Footer({ incMetric }) {
  const { isMobile } = useViewport();
  return (
    <footer id="contatti" style={{ background: C.ink, color: C.white }}>

      {/* Links */}
      <div style={{ padding: isMobile ? '40px 20px 28px' : '56px 48px 36px', maxWidth: 1280, margin: '0 auto' }}>
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr 1fr' : '2fr 1fr 1fr 1fr', gap: isMobile ? 28 : 48 }}>
          <div style={{ gridColumn: isMobile ? '1 / -1' : 'auto' }}>
            <Logo variant="white" height={34}/>
            <p style={{ fontFamily: FONT.sans, fontSize: 13, lineHeight: 1.55, opacity: 0.6, marginTop: 18, maxWidth: 340 }}>
              Un evento di FaventiaX APS. Edizione zero, fine 2026.<br/>Faenza · Romagna · Italia.
            </p>
          </div>
          {[
            ['Naviga', [['Home', '#/'], ['Chi siamo', '#/chi-siamo'], ['Diventa partner', '#/partner'], ['Speaker', '#/speaker']]],
            ['Scrivici', [[MAIL.partner, `mailto:${MAIL.partner}`], [MAIL.staff, `mailto:${MAIL.staff}`], [MAIL.news, `mailto:${MAIL.news}`]]],
            ['TED ufficiale', [['TED.com', 'https://www.ted.com'], ['Programma TEDx', 'https://www.ted.com/about/programs-initiatives/tedx-program'], ['TEDx Rules', 'https://www.ted.com/about/programs-initiatives/tedx-program/tedx-rules']]],
          ].map(([h, items]) => (
            <div key={h} style={{ fontFamily: FONT.sans, fontSize: 12 }}>
              <div style={{ fontFamily: FONT.mono, fontSize: 10, letterSpacing: '0.16em', textTransform: 'uppercase', opacity: 0.5, marginBottom: 14 }}>{h}</div>
              <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 9 }}>
                {items.map(([l, hr]) => (
                  <li key={l}><a href={hr} target={hr.startsWith('http') ? '_blank' : undefined} rel="noopener" data-cursor className="ulink" style={{ color: C.white, textDecoration: 'none', opacity: 0.8 }}>{l}</a></li>
                ))}
              </ul>
            </div>
          ))}
        </div>
        <div style={{ marginTop: 56, paddingTop: 22, borderTop: '1px solid rgba(255,255,255,0.14)', display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 14, fontFamily: FONT.mono, fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', opacity: 0.55 }}>
          <div>This independent TEDx event is operated under license from TED.</div>
          <div>© 2026 FaventiaX APS · tedxfaenza.it</div>
        </div>
      </div>
    </footer>
  );
}
window.Footer = Footer;

// Phase switch — inline pill control used on the Home page
function PhaseSwitch({ phase, setPhase, incMetric }) {
  const { isMobile } = useViewport();
  const opts = [
    { v: 'partner', label: 'Diventa partner', sub: 'Stiamo cercando le imprese che credono in noi' },
    { v: 'public', label: 'Vivi l\'evento', sub: 'Speaker, programma e biglietti' },
  ];
  return (
    <div style={{ display: isMobile ? 'flex' : 'inline-flex', width: isMobile ? '100%' : 'auto', background: C.paperDeep, borderRadius: 999, padding: 4, gap: 4 }}>
      {opts.map((o) => {
        const active = phase === o.v;
        return (
          <button key={o.v} data-cursor onClick={() => { setPhase(o.v); incMetric && incMetric('clicks'); }}
            style={{
              border: 'none', cursor: 'pointer', borderRadius: 999, padding: isMobile ? '11px 14px' : '10px 22px',
              flex: isMobile ? 1 : 'none',
              background: active ? C.ink : 'transparent', color: active ? C.white : C.ink70,
              fontFamily: FONT.sans, fontSize: 13, fontWeight: 600, letterSpacing: '0.01em', whiteSpace: 'nowrap',
              transition: 'background .25s, color .25s',
            }}>
            {o.label}
          </button>
        );
      })}
    </div>
  );
}
window.PhaseSwitch = PhaseSwitch;
