// BeHueman — Enhancements: theme toggle, skeletons, search overlay (Cmd+K)

// ==========================================================
// Skeleton helpers — lightweight loading placeholders
// ==========================================================
function Skel({ w='100%', h=12, r=6, style }) {
  return <span className="skel" style={{ width:w, height:h, borderRadius:r, ...(style||{}) }}/>;
}
function SkelText({ lines=3, last='60%' }) {
  return (
    <div className="skel-stack">
      {Array.from({length: lines}).map((_,i) => (
        <Skel key={i} h={12} w={i === lines-1 ? last : '100%'}/>
      ))}
    </div>
  );
}
function SkelCard() {
  return (
    <div className="skel-card">
      <div className="row gap-12 mb-16" style={{alignItems:'center'}}>
        <Skel w={40} h={40} r={20}/>
        <div style={{flex:1}}>
          <Skel h={14} w={'45%'}/>
          <Skel h={11} w={'25%'} style={{marginTop:6}}/>
        </div>
      </div>
      <SkelText lines={3} last="70%"/>
    </div>
  );
}
function SkelTile() {
  return (
    <div className="skel-card" style={{padding:0, overflow:'hidden'}}>
      <Skel h={140} r={0}/>
      <div style={{padding:14}}>
        <Skel h={11} w={'30%'}/>
        <Skel h={16} w={'85%'} style={{marginTop:8}}/>
        <Skel h={11} w={'50%'} style={{marginTop:6}}/>
      </div>
    </div>
  );
}
function SkelPage({ kind='feed' }) {
  if (kind === 'tiles') {
    return (
      <div className="page">
        <div style={{marginBottom:32}}>
          <Skel h={11} w={120}/>
          <Skel h={36} w={'45%'} style={{marginTop:10}}/>
          <Skel h={14} w={'60%'} style={{marginTop:14}}/>
        </div>
        <div style={{display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(220px, 1fr))', gap:14}}>
          {Array.from({length:8}).map((_,i) => <SkelTile key={i}/>)}
        </div>
      </div>
    );
  }
  if (kind === 'detail') {
    return (
      <div className="page">
        <Skel h={28} w={120} style={{marginBottom:24}}/>
        <Skel h={220} r={16} style={{marginBottom:24}}/>
        <Skel h={36} w={'70%'} style={{marginBottom:14}}/>
        <Skel h={14} w={'40%'} style={{marginBottom:24}}/>
        <SkelText lines={5} last="55%"/>
      </div>
    );
  }
  // feed
  return (
    <div className="page">
      <div style={{marginBottom:32}}>
        <Skel h={11} w={120}/>
        <Skel h={36} w={'45%'} style={{marginTop:10}}/>
        <Skel h={14} w={'60%'} style={{marginTop:14}}/>
      </div>
      <div className="skel-stack">
        {Array.from({length:3}).map((_,i) => <SkelCard key={i}/>)}
      </div>
    </div>
  );
}

// Wrapper that shows a skeleton briefly when route changes, then the real screen
function RouteFader({ route, children, skelKind='feed' }) {
  const [loading, setLoading] = useState(true);
  const prev = React.useRef(route);
  if (prev.current !== route) { prev.current = route; }
  useEffect(() => {
    setLoading(true);
    const t = setTimeout(() => setLoading(false), 240);
    return () => clearTimeout(t);
  }, [route]);
  return loading ? <SkelPage kind={skelKind}/> : children;
}

// ==========================================================
// Theme toggle (light ↔ dark)
// ==========================================================
function ThemeToggle() {
  const [dark, setDark] = useState(() => {
    try { return localStorage.getItem('bh-theme') === 'dark'; } catch (e) { return false; }
  });
  useEffect(() => {
    document.documentElement.setAttribute('data-theme', dark ? 'dark' : 'light');
    document.body.setAttribute('data-theme', dark ? 'dark' : 'light');
    // Imperative override — iframe host injects high-specificity body styles
    if (dark) {
      document.body.style.setProperty('background', '#14110D', 'important');
      document.body.style.setProperty('color', '#F2EAD8', 'important');
    } else {
      document.body.style.removeProperty('background');
      document.body.style.removeProperty('color');
    }
    const sb = document.querySelector('.sidebar');
    if (sb) {
      if (dark) {
        sb.style.setProperty('background', '#1C1813', 'important');
        sb.style.setProperty('border-right-color', '#2C2820', 'important');
      } else {
        sb.style.removeProperty('background');
        sb.style.removeProperty('border-right-color');
      }
    }
    try { localStorage.setItem('bh-theme', dark ? 'dark' : 'light'); } catch (e) {}
  }, [dark]);
  return (
    <button className="theme-toggle" onClick={()=>setDark(d => !d)} title={dark ? 'Tryb jasny' : 'Tryb ciemny'} aria-label="Przełącz motyw">
      <span className="knob">{dark ? '🌙' : '☀'}</span>
    </button>
  );
}

// ==========================================================
// Search overlay (Cmd+K)
// ==========================================================
function SearchOverlay({ onClose, onNavigate }) {
  const [q, setQ] = useState('');
  const [active, setActive] = useState(0);
  const inputRef = React.useRef(null);
  useEffect(() => { setTimeout(() => inputRef.current && inputRef.current.focus(), 30); }, []);

  // Build search index from AppData
  const index = React.useMemo(() => {
    const items = [];
    (AppData.authors || []).forEach(a => items.push({
      kind:'author', id:a.id, title:a.name, sub:`@${a.handle} · ${a.role}${a.verified?' · Verified':''}`,
      avatar:a, payload:a,
    }));
    (AppData.posts || []).forEach(p => items.push({
      kind:'post', id:p.id, title:p.title || (p.body || '').slice(0,80) || 'Post',
      sub:`Post · ${AppData.getAuthor(p.authorId).name}`, payload:p,
    }));
    (AppData.events || []).forEach(e => items.push({
      kind:'event', id:e.id, title:e.title, sub:`${e.type} · ${e.author} · ${e.date}`, payload:e,
      cover:e.cover,
    }));
    (AppData.eduTiles || []).forEach(t => items.push({
      kind:'course', id:t.id, title:t.title, sub:`${t.type} · ${t.author}`, payload:t,
      cover:t.cover,
    }));
    (AppData.domains || []).forEach(d => items.push({
      kind:'domain', id:d.id, title:d.label, sub:`Dziedzina · ${d.subs.length} pod-dziedzin`, payload:d,
      hue:d.hue,
    }));
    return items;
  }, []);

  // Quick actions when search is empty
  const quickActions = [
    { kind:'route', id:'community',  title:'Społeczność', sub:'Strumień postów',          route:'community' },
    { kind:'route', id:'authors',    title:'Katalog autorów', sub:'Wszyscy verified',     route:'authors' },
    { kind:'route', id:'events',     title:'Wydarzenia', sub:'Warsztaty, retreaty',       route:'events' },
    { kind:'route', id:'library',    title:'Twoja biblioteka', sub:'Zapisane i kupione',  route:'library' },
    { kind:'route', id:'settings',   title:'Ustawienia', sub:'Konto, prywatność',         route:'settings' },
  ];

  const norm = (s) => (s||'').toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g,'');
  const qq = norm(q.trim());
  const filtered = qq.length === 0 ? [] : index.filter(it =>
    norm(it.title).includes(qq) || norm(it.sub).includes(qq)
  ).slice(0, 18);
  const list = qq.length === 0 ? quickActions : filtered;

  const grouped = {};
  list.forEach(it => { (grouped[it.kind] = grouped[it.kind] || []).push(it); });
  const kindOrder = ['route','author','post','event','course','domain'];
  const kindLabels = { author:'Autorzy', post:'Posty', event:'Wydarzenia', course:'Edukacja', domain:'Dziedziny', route:'Sekcje' };

  // Flatten ordered for keyboard nav
  const flat = [];
  kindOrder.forEach(k => (grouped[k] || []).forEach(it => flat.push(it)));

  useEffect(() => {
    const handler = (e) => {
      if (e.key === 'Escape') { onClose(); }
      else if (e.key === 'ArrowDown') { e.preventDefault(); setActive(a => Math.min(flat.length - 1, a + 1)); }
      else if (e.key === 'ArrowUp')   { e.preventDefault(); setActive(a => Math.max(0, a - 1)); }
      else if (e.key === 'Enter')     { const it = flat[active]; if (it) pick(it); }
    };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  });

  function pick(it) {
    onClose();
    if (it.kind === 'route')  onNavigate({ type:'route', route: it.route });
    else if (it.kind === 'author') window.openDetail && window.openDetail('author', it.payload);
    else if (it.kind === 'event')  window.openDetail && window.openDetail('event', it.payload);
    else if (it.kind === 'course') window.openDetail && window.openDetail('course', it.payload);
    else if (it.kind === 'domain') onNavigate({ type:'route', route:'community' });
    else if (it.kind === 'post')   onNavigate({ type:'route', route:'community' });
  }

  function highlight(s) {
    if (!qq) return s;
    const i = norm(s).indexOf(qq);
    if (i < 0) return s;
    return <>{s.slice(0,i)}<mark>{s.slice(i, i+qq.length)}</mark>{s.slice(i+qq.length)}</>;
  }

  let runningIdx = -1;

  return (
    <div className="search-overlay" onClick={onClose}>
      <div className="search-panel" onClick={(e)=>e.stopPropagation()}>
        <div className="search-panel-input">
          <I name="Search" size={18}/>
          <input ref={inputRef} value={q} onChange={e=>{setQ(e.target.value); setActive(0);}} placeholder="Szukaj autorów, postów, wydarzeń, kursów…"/>
          <span className="kbd">esc</span>
        </div>
        <div className="search-panel-body">
          {qq.length > 0 && flat.length === 0 && (
            <div className="search-empty">
              <div style={{fontSize:32, marginBottom:8}}>🌿</div>
              <div style={{fontWeight:600, color:'var(--ink-1)'}}>Brak wyników</div>
              <div style={{fontSize:12.5, marginTop:4}}>Spróbuj innej frazy. Szukaj imienia autora, tytułu kursu lub wydarzenia.</div>
            </div>
          )}
          {kindOrder.map(k => {
            const arr = grouped[k];
            if (!arr || !arr.length) return null;
            return (
              <div key={k}>
                <div className="search-section">{kindLabels[k]}</div>
                {arr.map(it => {
                  runningIdx++;
                  const idx = runningIdx;
                  return (
                    <button
                      key={`${it.kind}-${it.id}`}
                      className={`search-result ${idx === active ? 'kbd-active' : ''}`}
                      onMouseEnter={()=>setActive(idx)}
                      onClick={()=>pick(it)}
                    >
                      {it.kind === 'author' && <Avatar author={it.avatar} size={32}/>}
                      {(it.kind === 'event' || it.kind === 'course') && (
                        <div style={{width:32, height:32, borderRadius:8, background:`linear-gradient(135deg, ${it.cover[0]}, ${it.cover[1]})`, flexShrink:0}}/>
                      )}
                      {it.kind === 'domain' && (
                        <div style={{width:32, height:32, borderRadius:8, background:`var(--hue-${it.hue})`, opacity:.8, flexShrink:0}}/>
                      )}
                      {it.kind === 'route' && (
                        <div style={{width:32, height:32, borderRadius:8, background:'var(--bg-soft)', display:'grid', placeItems:'center', flexShrink:0, color:'var(--ink-3)'}}>
                          <I name={it.route === 'community' ? 'Community' : it.route === 'authors' ? 'Sparkle' : it.route === 'events' ? 'Calendar' : it.route === 'library' ? 'Library' : 'Settings'} size={14}/>
                        </div>
                      )}
                      {it.kind === 'post' && (
                        <div style={{width:32, height:32, borderRadius:8, background:'var(--bg-soft)', display:'grid', placeItems:'center', flexShrink:0, color:'var(--ink-3)'}}>
                          <I name="Edit" size={14}/>
                        </div>
                      )}
                      <div className="search-result-meta">
                        <div className="search-result-title">{highlight(it.title)}</div>
                        <div className="search-result-sub">{highlight(it.sub)}</div>
                      </div>
                      <span className="search-result-kind">{kindLabels[it.kind].slice(0,-1) || it.kind}</span>
                    </button>
                  );
                })}
              </div>
            );
          })}
        </div>
        <div className="search-foot">
          <span><span className="kbd">↑</span> <span className="kbd">↓</span> nawiguj</span>
          <span><span className="kbd">↵</span> otwórz</span>
          <span style={{marginLeft:'auto'}}><span className="kbd">⌘</span> <span className="kbd">K</span> otwórz wyszukiwarkę</span>
        </div>
      </div>
    </div>
  );
}

// Hook to manage Cmd+K globally
function useSearchHotkey(open) {
  useEffect(() => {
    const handler = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
        e.preventDefault();
        open();
      }
    };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [open]);
}

Object.assign(window, { Skel, SkelText, SkelCard, SkelTile, SkelPage, RouteFader, ThemeToggle, SearchOverlay, useSearchHotkey });
