/* FreeToolzHub — app shell: hash router, theme, toasts, search overlay */
function SearchOverlay({ open, onClose, go }) {
  const { Icon } = window.DesignSystem_3a7ab0;
  const { TOOLS } = window.FTH;
  const [q, setQ] = React.useState('');
  const inputRef = React.useRef(null);
  React.useEffect(() => { if (open) { setQ(''); setTimeout(()=>inputRef.current && inputRef.current.focus(), 60); } }, [open]);
  if (!open) return null;
  const list = (q ? TOOLS.filter(t => (t.title+' '+t.desc+' '+t.cat).toLowerCase().includes(q.toLowerCase())) : TOOLS.filter(t=>t.working)).slice(0,9);
  return (
    <div onClick={onClose} style={{ position:'fixed', inset:0, zIndex:100, background:'rgba(8,15,30,.55)', backdropFilter:'blur(6px)', display:'grid', alignItems:'start', justifyItems:'center', paddingTop:'11vh' }}>
      <div onClick={e=>e.stopPropagation()} style={{ width:'min(640px,92vw)', background:'var(--bg-card)', border:'1px solid var(--border-color)', borderRadius:'var(--radius-2xl)', boxShadow:'var(--shadow-xl)', padding:14 }}>
        <div style={{ display:'flex', alignItems:'center', gap:12, padding:'6px 8px 14px', borderBottom:'1px solid var(--border-color)' }}>
          <Icon name="search" size={22} style={{ color:'var(--text-muted)' }} />
          <input ref={inputRef} value={q} onChange={e=>setQ(e.target.value)} placeholder="Search tools — e.g. compress, merge, summarize…"
            style={{ flex:1, border:'none', outline:'none', background:'none', fontFamily:'var(--font-heading)', fontSize:19, color:'var(--text-strong)' }} />
          <button onClick={onClose} style={{ border:'none', background:'var(--bg-subtle)', borderRadius:'var(--radius-md)', width:34, height:34, cursor:'pointer', display:'grid', placeItems:'center', color:'var(--text-muted)' }}><Icon name="x" size={18} /></button>
        </div>
        <div style={{ maxHeight:'52vh', overflowY:'auto', marginTop:8, display:'flex', flexDirection:'column', gap:2 }}>
          {list.length ? list.map(t => {
            const [bg,fg] = window.FTH.TONE_MAP[t.tone];
            return (
              <a key={t.id} onClick={()=>{ onClose(); go('/tool/'+t.id); }} style={{ display:'flex', alignItems:'center', gap:14, padding:'11px 12px', borderRadius:'var(--radius-lg)', cursor:'pointer' }}
                onMouseEnter={e=>e.currentTarget.style.background='var(--bg-subtle)'} onMouseLeave={e=>e.currentTarget.style.background='transparent'}>
                <span style={{ width:42, height:42, borderRadius:'var(--radius-md)', background:bg, color:fg, display:'grid', placeItems:'center', flexShrink:0 }}><Icon name={t.icon} size={21} /></span>
                <span style={{ flex:1, minWidth:0 }}>
                  <span style={{ display:'block', fontFamily:'var(--font-heading)', fontWeight:600, fontSize:15, color:'var(--text-strong)' }}>{t.title}</span>
                  <span style={{ display:'block', fontSize:13, color:'var(--text-muted)' }}>{t.desc}</span>
                </span>
                <span style={{ fontSize:12, fontWeight:700, color:'var(--text-muted)', padding:'4px 10px', borderRadius:'var(--radius-full)', background:'var(--bg-subtle)' }}>{window.FTH.catLabel(t.cat)}</span>
              </a>
            );
          }) : <div style={{ padding:30, textAlign:'center', color:'var(--text-muted)' }}>No tools match “{q}”.</div>}
        </div>
      </div>
    </div>
  );
}

function parseHash() {
  const h = (location.hash || '#/').replace(/^#/, '');
  const parts = h.split('/').filter(Boolean); // ['tool','merge-pdf']
  if (!parts.length) return { name:'home' };
  if (parts[0]==='tools') return { name:'tools', cat: parts[1] || 'all' };
  if (parts[0]==='tool') return { name:'tool', id: parts[1] };
  return { name:'home' };
}

function App() {
  const [route, setRoute] = React.useState(parseHash());
  const [dark, setDark] = React.useState(localStorage.getItem('fth-theme')==='dark');
  const [search, setSearch] = React.useState(false);
  const [toasts, setToasts] = React.useState([]);
  const { Toast } = window.DesignSystem_3a7ab0;

  React.useEffect(() => {
    document.documentElement.setAttribute('data-theme', dark ? 'dark' : 'light');
    localStorage.setItem('fth-theme', dark ? 'dark' : 'light');
  }, [dark]);

  React.useEffect(() => {
    const onHash = () => { setRoute(parseHash()); window.scrollTo({ top:0 }); };
    window.addEventListener('hashchange', onHash);
    const onKey = (e) => {
      if (e.key==='/' && !/input|textarea/i.test(document.activeElement.tagName)) { e.preventDefault(); setSearch(true); }
      if (e.key==='Escape') setSearch(false);
    };
    window.addEventListener('keydown', onKey);
    return () => { window.removeEventListener('hashchange', onHash); window.removeEventListener('keydown', onKey); };
  }, []);

  const go = (path) => { location.hash = '#'+path; };
  const pushToast = (message) => {
    const id = Math.random().toString(36).slice(2);
    setToasts(t => [...t, { id, message }]);
    setTimeout(() => setToasts(t => t.filter(x => x.id!==id)), 2600);
  };

  let page;
  if (route.name==='tools') page = <window.FTHToolsBrowse go={go} initialCat={route.cat} />;
  else if (route.name==='tool') page = <window.FTHToolPage go={go} toolId={route.id} pushToast={pushToast} />;
  else page = <window.FTHHome go={go} />;

  return (
    <div>
      <window.FTHHeader go={go} dark={dark} setDark={setDark} onSearch={()=>setSearch(true)} />
      {page}
      <window.FTHFooter go={go} />
      <SearchOverlay open={search} onClose={()=>setSearch(false)} go={go} />
      <div style={{ position:'fixed', bottom:24, right:24, zIndex:120, display:'flex', flexDirection:'column', gap:10 }}>
        {toasts.map(t => <Toast key={t.id} title={t.message} tone="success" />)}
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
