/* Top bar, Home (hero + prompt + clients + tiles), Footer. */
const { useState: useStateHome, useEffect: useEffectHome, useRef: useRefHome } = React;

function TopBar({ active, onNavigate, dark, onToggleGlass }) {
  const [scrolled, setScrolled] = useStateHome(false);
  const [open, setOpen] = useStateHome(false);
  useEffectHome(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  // While the mobile menu is open: close on Escape or a tap outside it.
  useEffectHome(() => {
    if (!open) return;
    const onDown = (e) => { if (!e.target.closest('.wmenu-wrap')) setOpen(false); };
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    document.addEventListener('pointerdown', onDown);
    window.addEventListener('keydown', onKey);
    return () => { document.removeEventListener('pointerdown', onDown); window.removeEventListener('keydown', onKey); };
  }, [open]);
  const go = (key) => { setOpen(false); onNavigate(key); };
  return (
    <header className={'topbar' + (scrolled ? ' scrolled' : '')}>
      <div className="shell topbar-inner">
        <button className="brand" onClick={() => go('home')} aria-label="Home">
          <span className="mark"><Mark size={30} /></span>
          <span className="wm">
            <span className="n">{DATA.person.name}</span>
            <span className="r">Club of Curiouser</span>
          </span>
        </button>
        <div className={'wmenu-wrap' + (open ? ' open' : '')}>
          <nav className="wmenu" id="wmenu">
            {DATA.nav.map((item) =>
            <button key={item.key}
            className={'witem' + (active === item.key ? ' active' : '')}
            data-key={item.key}
            onClick={() => go(item.key)}>
                {item.label}<span className="full"> {item.full}</span>
              </button>
            )}
          </nav>
          <button className="glass-toggle" onClick={onToggleGlass} aria-label="Toggle looking-glass mode" title="Looking-glass mode">
            <Icon name={dark ? 'sun' : 'moon'} size={16} />
          </button>
          <button className="menu-toggle" onClick={() => setOpen((o) => !o)}
          aria-label={open ? 'Close menu' : 'Open menu'} aria-expanded={open} aria-controls="wmenu">
            <Icon name={open ? 'x' : 'menu'} size={20} />
          </button>
        </div>
      </div>
    </header>);

}

function Prompt({ onNavigate }) {
  const [val, setVal] = useStateHome('');
  const [focused, setFocused] = useStateHome(false);
  const [thinking, setThinking] = useStateHome(false);
  const [ph, setPh] = useStateHome(0);
  const inputRef = useRefHome(null);

  // rotating placeholder for the generative feel
  useEffectHome(() => {
    if (val || focused) return;
    const t = setInterval(() => setPh((p) => (p + 1) % DATA.suggestions.length), 2800);
    return () => clearInterval(t);
  }, [val, focused]);

  const route = (() => {
    const q = val.toLowerCase();
    if (!q.trim()) return null;
    let best = null,bestScore = 0;
    DATA.routes.forEach((r) => {
      const score = r.words.reduce((s, w) => s + (q.includes(w) ? 1 : 0), 0);
      if (score > bestScore) {bestScore = score;best = r.to;}
    });
    return best;
  })();
  const targetKey = route || 'what';
  const targetItem = DATA.nav.find((n) => n.key === targetKey);
  const targetFull = targetItem ? targetItem.label + ' ' + targetItem.full : '';

  const go = () => {
    if (!val.trim()) {inputRef.current?.focus();return;}
    setThinking(true);
    setTimeout(() => {setThinking(false);onNavigate(targetKey);}, 680);
  };

  return (
    <div className={'prompt' + (focused ? ' focused' : '') + (thinking ? ' thinking' : '')}>
      <div className="prompt-top">
        <span className="ico"><Icon name="sparkle" size={24} /></span>
        <input
          ref={inputRef}
          value={val}
          onChange={(e) => setVal(e.target.value)}
          onFocus={() => setFocused(true)}
          onBlur={() => setFocused(false)}
          onKeyDown={(e) => {if (e.key === 'Enter') go();}}
          placeholder={DATA.suggestions[ph].text}
          aria-label="Ask my work anything" />
        
      </div>
      <div className="prompt-bar">
        <span className="prompt-hint">
          {thinking ?
          'Curiouser… finding the right door' :
          route ?
          <>↵ opens <b>{targetFull}</b></> :
          val.trim() ?
          <>↵ opens <b>{targetFull}</b></> :
          'Type a question, or pick from below'}
        </span>
        <button className="prompt-send" onClick={go} disabled={!val.trim()} aria-label="Ask">
          <Icon name="arrow-up" size={18} />
        </button>
      </div>
    </div>);

}

function Clients() {
  const loop = [...DATA.logos, ...DATA.logos];
  return (
    <section className="clients reveal">
      <div className="lbl"><span className="eyebrow">HOUSES OF WORK AND WONDER</span></div>
      <div className="logo-marquee">
        <div className="logo-track">
          {loop.map((logo, i) =>
          <div className="logo-slot" key={i} aria-hidden={i >= DATA.logos.length ? 'true' : undefined}>
              <img className="logo-img" src={logo.file} alt={logo.name} loading="lazy" style={logo.h ? { maxHeight: logo.h + 'px' } : undefined} />
            </div>
          )}
        </div>
      </div>
    </section>);

}

function Tiles({ layout, onNavigate }) {
  const content = {
    how: { num: 'HOW', title: 'How to collaborate', teaser: 'Five+ moves, borrowed from strategy and bent toward design.' },
    which: { num: 'WHICH', title: 'Which artefacts to use', teaser: 'The wonderful stuff underneath the visual tip of an iceberg.' },
    who: { num: 'WHO', title: 'Who I am', teaser: '“I know who I was when I got up this morning, but I think I must have been changed several times since then.”' },
    why: { num: 'WHY', title: 'Why I love designing', teaser: 'Creativity as a problem-solving instrument, not just making it nice.' },
    what: { num: 'WHAT', title: 'What I have created', teaser: 'Portfolio or perspective, pick me.' },
    where: { num: 'WHERE', title: 'Where is the white rabbit?', teaser: 'The places I keep returning to.' }
  };
  const tiles = DATA.tiles.map((key) => ({ key, ...content[key] }));
  return (
    <section>
      <div className="doors-head reveal">
        <h2>Pick your curiosity</h2>
        <span className="note"></span>
      </div>
      <div className={'doors ' + layout + '-layout reveal'}>
        {tiles.map((t) => layout === 'index' ?
        <button className="door" key={t.key} onClick={() => onNavigate(t.key)}>
            <span className="d-num">{t.num}</span>
            <span>
              <span className="d-word">{t.title}</span>
            </span>
            <span className="d-teaser">{t.teaser}</span>
            <span className="d-foot"><span className="arr"><Icon name="arrow-right" size={15} /></span></span>
          </button> :

        <button className="door" key={t.key} onClick={() => onNavigate(t.key)}>
            <span className="d-num">{t.num}</span>
            <span className="d-word">{t.title}</span>
            <span className="d-teaser">{t.teaser}</span>
            <span className="d-foot">Open <span className="arr"><Icon name="arrow-right" size={13} /></span></span>
          </button>
        )}
      </div>
    </section>);

}

function Home({ tweaks, onNavigate }) {
  return (
    <div className="home">
      <div className="shell">
        <section className="hero">
          <div className="aura"><Mark size={820} /></div>
          <span className="kicker"><span className="dot"></span><span className="eyebrow">14-YEAR EXPERIENCE & THE POWER OF CURIOSITY</span></span>
          <h1>Ask me <em>anything</em>.</h1>
          <Prompt onNavigate={onNavigate} />
          <div className="chips">
            {DATA.suggestions.map((s, i) =>
            <button className="chip" key={i} data-to={s.to} onClick={() => onNavigate(s.to)}>
                {s.text}<span className="arr"><Icon name="arrow-right" size={13} /></span>
              </button>
            )}
          </div>
        </section>
        <Clients />
        <Tiles layout={tweaks.tiles} onNavigate={onNavigate} />
      </div>
      <Footer onNavigate={onNavigate} />
    </div>);

}

function Footer({ onNavigate }) {
  return (
    <footer className="foot">
      <div className="shell">
        <div className="foot-grid">
          <div className="fcol">
            <span className="mark" style={{ display: 'inline-block', width: 34, height: 34, color: 'var(--fg)' }}><Mark size={34} /></span>
            <p className="blurb">Club of Curiouser<br />Curiouser and curiouser</p>
          </div>
          <div className="fcol">
            <div className="h">The doors</div>
            {DATA.nav.map((n) => <button key={n.key} onClick={() => onNavigate(n.key)}>{n.short}</button>)}
          </div>
          <div className="fcol">
            <div className="h">Elsewhere</div>
            <button onClick={() => onNavigate('when')}>{DATA.person.email}</button>
            <span style={{ fontSize: 14, color: 'var(--fg-muted)', padding: '4px 0', display: 'block' }}>{DATA.person.location}</span>
          </div>
        </div>
        <div className="foot-bottom">
          <span>© {new Date().getFullYear()} {DATA.person.name}</span>
          <span>Built with AI · Design by heart</span>
        </div>
      </div>
    </footer>);

}

Object.assign(window, { TopBar, Home, Footer });