/* RINAU HEX — Sector Explorer (3 rutas) + Command Palette (Ctrl/Cmd+K) */

const { useState: useStateE, useEffect: useEffectE, useRef: useRefE } = React;

/* ---- text normalize: lowercase, strip accents ---- */
function rhxNormalize(s) {
  return (s || '').toString().toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '');
}
function rhxWordMatch(hay, word) {
  if (hay.includes(word)) return true;
  if (word.endsWith('s') && hay.includes(word.slice(0, -1))) return true;
  if (!word.endsWith('s') && hay.includes(word + 's')) return true;
  return false;
}
function rhxServiceHaystack(s) {
  const parts = [
    s.title?.es, s.title?.en, s.description?.es, s.description?.en,
    ...(s.details?.es || []), ...(s.details?.en || []),
  ];
  for (const lang of ['es','en']) {
    const cats = window.RHX.ui[lang].portfolio.cats;
    const c = cats.find(x => x.id === s.category);
    if (c) parts.push(c.label);
    const subs = window.RHX.ui[lang].portfolio.subcats[s.category] || [];
    const sub = subs.find(x => x.id === s.subcategory);
    if (sub) parts.push(sub.label);
  }
  return rhxNormalize(parts.join(' '));
}
function rhxServiceMatchesQuery(s, words) {
  if (!words.length) return true;
  const hay = rhxServiceHaystack(s);
  return words.every(w => rhxWordMatch(hay, w));
}
window.rhxNormalize = rhxNormalize;
window.rhxServiceMatchesQuery = rhxServiceMatchesQuery;

/* ============== SECTOR EXPLORER ============== */
function SectorExplorer() {
  const { lang } = window.useApp();
  const t = window.RHX.ui[lang].portfolio;
  const I = window.RHX_ICONS;

  const goToSector = (id) => {
    window.dispatchEvent(new CustomEvent('rhx:filter-category', { detail: { category: id } }));
    document.getElementById('services')?.scrollIntoView({ block: 'start' });
  };
  const goAll = () => {
    window.dispatchEvent(new CustomEvent('rhx:filter-category', { detail: { category: 'all' } }));
    document.getElementById('services')?.scrollIntoView({ block: 'start' });
  };

  return (
    <section className="bg-white dark:bg-[#06090F] border-b border-gray-100 dark:border-white/5">
      <div className="max-w-7xl mx-auto px-6 lg:px-10 py-20 lg:py-24">
        <div className="text-center max-w-2xl mx-auto mb-14">
          <div className="text-[11px] font-mono tracking-[0.24em] text-[#14B8A6] uppercase mb-4">// {t.explorer.kicker}</div>
          <h2 className="font-display font-medium text-3xl lg:text-5xl text-gray-900 dark:text-white tracking-tight leading-tight text-balance">{t.explorer.title}</h2>
          <p className="text-gray-500 dark:text-gray-400 mt-4 text-sm leading-relaxed">{t.explorer.sub}</p>
        </div>

        {/* Hub */}
        <div className="hidden lg:flex flex-col items-center mb-2">
          <svg viewBox="0 0 40 40" className="w-12 h-12 text-[#14B8A6]">
            <polygon points="20,2 36,11 36,29 20,38 4,29 4,11" fill="none" stroke="currentColor" strokeWidth="1.5"/>
            <circle cx="20" cy="20" r="3" fill="currentColor"/>
          </svg>
          <div className="font-mono text-[9px] text-gray-400 dark:text-gray-600 tracking-widest uppercase mt-2">RINAU HEX</div>
          <div className="w-px h-10 bg-gradient-to-b from-[#14B8A6]/60 to-transparent mt-2"></div>
        </div>

        <div className="grid sm:grid-cols-3 gap-5 lg:gap-6 relative">
          <div className="hidden lg:block absolute left-0 right-0 top-0 h-px bg-gradient-to-r from-transparent via-[#14B8A6]/30 to-transparent"></div>
          {t.explorer.nodes.map((n, i) => {
            const icon = n.id === 'academic' ? 'GraduationCap' : n.id === 'enterprise' ? 'Briefcase' : 'HeartPulse';
            const Icon = I[icon] || I.Layers3;
            const count = window.RHX.services.filter(s => s.category === n.id).length;
            return (
              <button key={n.id} onClick={() => goToSector(n.id)}
                className="group relative text-left bg-gray-50 dark:bg-[#0B132B] border border-gray-200 dark:border-white/10 hover:border-[#14B8A6] rounded-2xl p-7 lg:p-8 transition-all hover:-translate-y-1">
                <span className="hidden lg:block absolute left-1/2 -translate-x-1/2 -top-[52px] w-px h-12 bg-gradient-to-b from-transparent to-[#14B8A6]/30 group-hover:to-[#14B8A6] transition-colors"></span>
                <div className="w-14 h-14 rounded-xl border border-[#14B8A6]/30 bg-white dark:bg-[#0A0F1A] text-[#14B8A6] flex items-center justify-center mb-6 group-hover:bg-[#14B8A6] group-hover:text-white transition-colors">
                  <Icon size={24}/>
                </div>
                <div className="font-mono text-[9px] text-gray-400 dark:text-gray-500 tracking-widest uppercase mb-2">{String(count).padStart(2,'0')} {lang==='es'?'servicios':'services'}</div>
                <h3 className="font-display font-medium text-xl text-gray-900 dark:text-white tracking-tight mb-2">{n.label}</h3>
                <p className="text-[13px] text-gray-500 dark:text-gray-400 leading-relaxed">{n.desc}</p>
                <div className="mt-5 inline-flex items-center gap-2 text-[11px] font-medium uppercase tracking-[0.14em] text-[#14B8A6]">
                  {lang==='es'?'Explorar':'Explore'} <I.ArrowRight size={13} className="group-hover:translate-x-1 transition-transform"/>
                </div>
              </button>
            );
          })}
        </div>

        <div className="text-center mt-10">
          <button onClick={goAll} className="inline-flex items-center gap-2 font-mono text-[11px] tracking-widest uppercase text-gray-500 hover:text-[#14B8A6] transition-colors">
            <I.Layers3 size={13}/>{t.explorer.exploreAll}
          </button>
        </div>
      </div>
    </section>
  );
}

/* ============== COMMAND PALETTE (Ctrl/Cmd+K) ============== */
function CommandPalette() {
  const { lang } = window.useApp();
  const t = window.RHX.ui[lang].portfolio;
  const I = window.RHX_ICONS;
  const [open, setOpen] = useStateE(false);
  const [q, setQ] = useStateE('');
  const inputRef = useRefE(null);

  useEffectE(() => {
    const onKey = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
        e.preventDefault();
        setOpen(o => !o);
      } else if (e.key === 'Escape') {
        setOpen(false);
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  useEffectE(() => {
    if (open) { setQ(''); setTimeout(()=>inputRef.current?.focus(), 30); }
  }, [open]);

  if (!open) return null;

  const words = window.rhxNormalize(q.trim()).split(/\s+/).filter(Boolean);
  const results = window.RHX.services.filter(s => window.rhxServiceMatchesQuery(s, words)).slice(0, 8);

  const openService = (id) => {
    setOpen(false);
    window.dispatchEvent(new CustomEvent('rhx:open-service', { detail: { id } }));
    document.getElementById('services')?.scrollIntoView({ block: 'start' });
  };

  return (
    <div className="fixed inset-0 z-[110] flex items-start justify-center pt-[12vh] p-4" role="dialog" aria-modal="true">
      <div onClick={()=>setOpen(false)} className="absolute inset-0 bg-black/70 backdrop-blur-sm"></div>
      <div className="relative w-full max-w-xl bg-white dark:bg-[#0B132B] border border-gray-200 dark:border-white/10 rounded-xl shadow-2xl overflow-hidden">
        <div className="flex items-center gap-3 px-5 py-4 border-b border-gray-100 dark:border-white/10">
          <I.Search size={16} className="text-[#14B8A6] shrink-0"/>
          <input ref={inputRef} value={q} onChange={(e)=>setQ(e.target.value)} placeholder={t.cmdk.placeholder}
            className="flex-1 bg-transparent outline-none text-[14px] text-gray-900 dark:text-white placeholder:text-gray-400"/>
          <kbd className="hidden sm:inline font-mono text-[10px] text-gray-400 border border-gray-200 dark:border-white/10 rounded px-1.5 py-0.5">ESC</kbd>
        </div>
        <div className="max-h-[50vh] overflow-y-auto">
          {q.trim() === '' ? (
            <div className="px-5 py-8 text-center font-mono text-[11px] text-gray-400">{t.cmdk.hint}</div>
          ) : results.length === 0 ? (
            <div className="px-5 py-8 text-center font-mono text-[11px] text-gray-400">{t.noResultsTitle}</div>
          ) : (
            <ul className="py-2">
              {results.map(s => {
                const Icon = I[s.icon] || I.Layers;
                return (
                  <li key={s.id}>
                    <button onClick={()=>openService(s.id)} className="w-full flex items-center gap-3 px-5 py-3 text-left hover:bg-gray-50 dark:hover:bg-[#11182B] transition-colors">
                      <span className="w-8 h-8 rounded-lg border border-[#14B8A6]/30 text-[#14B8A6] flex items-center justify-center shrink-0"><Icon size={15}/></span>
                      <span className="min-w-0">
                        <div className="text-[13px] font-medium text-gray-900 dark:text-white truncate">{s.title[lang]}</div>
                        <div className="text-[11px] text-gray-500 dark:text-gray-500 truncate">{s.description[lang]}</div>
                      </span>
                    </button>
                  </li>
                );
              })}
            </ul>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { SectorExplorer, CommandPalette });
