/* RINAU HEX — Portfolio (Services) Section: search, filters, grid, detail panel */

const { useState: useStateP, useEffect: useEffectP, useRef: useRefP, useMemo: useMemoP } = React;
const IP = window.RHX_ICONS;
const PAGE_SIZE = 24;

/* ============== SERVICE CARD ============== */
function ServiceCard({ s, lang, subLabel, catLabel, inCart, onOpen }) {
  const Icon = IP[s.icon] || IP.Layers;
  return (
    <div className="group h-full flex flex-col bg-white dark:bg-[#0F1729] border border-gray-200 dark:border-white/10 rounded-xl p-6 hover:border-[#14B8A6]/50 hover:-translate-y-0.5 transition-all">
      <div className="flex items-start justify-between mb-5">
        <div className="w-11 h-11 rounded-lg border border-[#14B8A6]/30 bg-gray-50 dark:bg-[#0B132B] text-[#14B8A6] flex items-center justify-center group-hover:bg-[#14B8A6] group-hover:text-white transition-colors">
          <Icon size={18}/>
        </div>
        {inCart && (
          <span className="inline-flex items-center gap-1 font-mono text-[9px] text-[#14B8A6] bg-[#14B8A6]/10 rounded-full px-2 py-1">
            <IP.Check size={10}/>
          </span>
        )}
      </div>
      <div className="font-mono text-[9px] tracking-widest text-gray-400 dark:text-gray-500 uppercase mb-2 truncate">{subLabel || catLabel}</div>
      <h3 className="font-display font-medium text-[15px] text-gray-900 dark:text-white tracking-tight leading-snug mb-2">{s.title[lang]}</h3>
      <p className="text-[13px] text-gray-500 dark:text-gray-400 leading-relaxed line-clamp-2 flex-1">{s.description[lang]}</p>
      <button onClick={()=>onOpen(s.id)} className="mt-5 inline-flex items-center gap-2 text-[11px] font-medium uppercase tracking-[0.14em] text-[#14B8A6] hover:gap-3 transition-all">
        {window.RHX.ui[lang].portfolio.viewBtn} <IP.ArrowRight size={13}/>
      </button>
    </div>
  );
}

/* ============== DETAIL PANEL ============== */
function ServiceDetailPanel({ id, onClose }) {
  const { lang, cart, addItem, removeItem } = window.useApp();
  const t = window.RHX.ui[lang].portfolio;
  const services = window.RHX.services;
  const s = services.find(x => x.id === id);
  const panelRef = useRefP(null);
  const closeBtnRef = useRefP(null);
  const [justAdded, setJustAdded] = useStateP(false);

  useEffectP(() => {
    closeBtnRef.current?.focus();
    const onKey = (e) => {
      if (e.key === 'Escape') { onClose(); return; }
      if (e.key === 'Tab' && panelRef.current) {
        const focusables = panelRef.current.querySelectorAll('button, a, input, textarea, select, [tabindex]:not([tabindex="-1"])');
        if (!focusables.length) return;
        const first = focusables[0], last = focusables[focusables.length-1];
        if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
        else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
      }
    };
    document.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => { document.removeEventListener('keydown', onKey); document.body.style.overflow = ''; };
  }, []);

  if (!s) return null;
  const Icon = IP[s.icon] || IP.Layers;
  const cat = t.cats.find(c=>c.id===s.category);
  const subs = t.subcats[s.category] || [];
  const sub = subs.find(x=>x.id===s.subcategory);
  const inCart = cart.includes(s.id);

  const handleAdd = () => { addItem(s.id); setJustAdded(true); setTimeout(()=>setJustAdded(false), 900); };

  return (
    <div className="fixed inset-0 z-[95]" role="dialog" aria-modal="true" aria-label={s.title[lang]}>
      <div onClick={onClose} className="absolute inset-0 bg-black/60 backdrop-blur-sm"></div>
      <div ref={panelRef}
        className="absolute inset-0 sm:inset-y-0 sm:right-0 sm:left-auto sm:w-[480px] lg:w-[560px] bg-white dark:bg-[#0B132B] shadow-2xl flex flex-col overflow-y-auto rhx-fade-right">
        <div className="sticky top-0 z-10 flex items-center justify-between px-6 py-5 border-b border-gray-100 dark:border-white/10 bg-white dark:bg-[#0B132B]">
          <div className="font-mono text-[10px] text-[#14B8A6] tracking-widest uppercase">// {s.id}</div>
          <button ref={closeBtnRef} onClick={onClose} aria-label={t.closeBtn}
            className="p-2 -m-2 text-gray-500 hover:text-gray-900 dark:hover:text-white transition-colors">
            <IP.X size={22}/>
          </button>
        </div>

        <div className="p-6 lg:p-8 flex-1">
          <div className="w-16 h-16 rounded-xl bg-[#14B8A6]/10 text-[#14B8A6] flex items-center justify-center border border-[#14B8A6]/30 mb-6">
            <Icon size={28}/>
          </div>
          <div className="flex flex-wrap items-center gap-2 mb-3">
            <span className="font-mono text-[10px] tracking-[0.16em] uppercase text-[#14B8A6] bg-[#14B8A6]/10 px-2.5 py-1 rounded-full">{cat?.label || s.category}</span>
            {sub && <span className="font-mono text-[10px] tracking-[0.16em] uppercase text-gray-500 dark:text-gray-400 bg-gray-100 dark:bg-white/5 px-2.5 py-1 rounded-full">{sub.label}</span>}
          </div>
          <h2 className="font-display font-medium text-2xl lg:text-[28px] text-gray-900 dark:text-white tracking-tight leading-tight mb-3">{s.title[lang]}</h2>
          <p className="text-sm text-gray-500 dark:text-gray-400 leading-relaxed mb-8">{s.description[lang]}</p>

          {s.image && (
            <div className="relative aspect-[16/9] rounded-xl bg-[#0B132B] overflow-hidden border border-gray-200 dark:border-white/10 mb-8">
              <img src={s.image} alt={s.title[lang]} className="w-full h-full object-cover opacity-90"
                referrerPolicy="no-referrer" onError={(e)=>{ e.target.closest('div').style.display='none'; }}/>
            </div>
          )}

          <div className="font-mono text-[10px] text-gray-400 uppercase tracking-widest flex items-center gap-1.5 mb-3">
            <IP.Info size={11} className="text-[#14B8A6]"/>{t.featLabel}
          </div>
          <ul className="space-y-2">
            {s.details[lang].map((d,i)=>(
              <li key={i} className="flex items-start gap-3 p-4 rounded-xl bg-gray-50 dark:bg-[#11182B] border border-gray-200 dark:border-white/5 text-[13px] text-gray-800 dark:text-gray-200 leading-relaxed">
                <span className="w-1.5 h-1.5 bg-[#14B8A6] rotate-45 shrink-0 mt-2"></span>
                <span>{d}</span>
              </li>
            ))}
          </ul>
        </div>

        <div className="sticky bottom-0 p-6 border-t border-gray-100 dark:border-white/10 bg-white dark:bg-[#0B132B] flex items-center gap-2">
          {inCart ? (
            <React.Fragment>
              <button disabled className={`flex-1 inline-flex items-center justify-center gap-2.5 px-6 py-4 rounded-xl bg-[#14B8A6]/15 text-[#14B8A6] font-medium text-[12px] uppercase tracking-[0.18em] cursor-default border border-[#14B8A6]/30 ${justAdded?'rhx-success-pop':''}`}>
                <IP.Check size={14}/> {t.addedBtn}
              </button>
              <button onClick={()=>removeItem(s.id)} title={lang==='es'?'Quitar de cotización':'Remove from quote'}
                className="inline-flex items-center justify-center gap-2 px-5 py-4 rounded-xl bg-transparent border border-[#EF4444]/40 text-[#EF4444] hover:bg-[#EF4444] hover:text-white font-medium text-[12px] uppercase tracking-[0.18em] transition-all">
                <IP.Trash size={14}/>
              </button>
            </React.Fragment>
          ) : (
            <button onClick={handleAdd}
              className="w-full inline-flex items-center justify-center gap-2.5 px-6 py-4 rounded-xl font-medium text-[12px] uppercase tracking-[0.18em] bg-[#14B8A6] hover:bg-[#0D9488] text-white transition-all">
              <IP.Plus size={14}/> {t.addBtn}
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

/* ============== PORTFOLIO (main section) ============== */
function Portfolio() {
  window.useAdmin();
  const { lang, cart } = window.useApp();
  const t = window.RHX.ui[lang].portfolio;
  const services = window.RHX.services;

  const [search, setSearch] = useStateP('');
  const [cat, setCat] = useStateP('all');
  const [subcat, setSubcat] = useStateP('all');
  const [page, setPage] = useStateP(0);
  const [detailId, setDetailId] = useStateP(null);

  /* Cross-component events: sector explorer + command palette */
  useEffectP(() => {
    const onFilterCat = (e) => { setCat(e.detail.category); setSubcat('all'); setPage(0); };
    const onOpenService = (e) => setDetailId(e.detail.id);
    window.addEventListener('rhx:filter-category', onFilterCat);
    window.addEventListener('rhx:open-service', onOpenService);
    return () => {
      window.removeEventListener('rhx:filter-category', onFilterCat);
      window.removeEventListener('rhx:open-service', onOpenService);
    };
  }, []);

  useEffectP(() => { setPage(0); }, [search, cat, subcat]);

  const subOptions = cat === 'all' ? [] : (t.subcats[cat] || []);

  const filtered = useMemoP(() => {
    const words = window.rhxNormalize(search.trim()).split(/\s+/).filter(Boolean);
    return services.filter(s =>
      (cat === 'all' || s.category === cat) &&
      (subcat === 'all' || s.subcategory === subcat) &&
      window.rhxServiceMatchesQuery(s, words)
    );
  }, [services, search, cat, subcat]);

  const totalPages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE));
  const safePage = Math.min(page, totalPages - 1);
  const visible = filtered.slice(safePage * PAGE_SIZE, safePage * PAGE_SIZE + PAGE_SIZE);

  const clearFilters = () => { setSearch(''); setCat('all'); setSubcat('all'); };
  const hasFilters = search.trim() !== '' || cat !== 'all' || subcat !== 'all';

  const catLabel = (id) => t.cats.find(c=>c.id===id)?.label || id;
  const subLabel = (s) => (t.subcats[s.category]||[]).find(x=>x.id===s.subcategory)?.label;

  return (
    <section id="services" className="bg-gray-50 dark:bg-[#0A0F1A] relative overflow-hidden">
      <div className="max-w-7xl mx-auto px-6 lg:px-10 py-24 lg:py-32">
        {/* Header */}
        <div className="grid lg:grid-cols-12 gap-8 mb-10 items-end">
          <div className="lg:col-span-7 space-y-5">
            <div className="text-[11px] font-mono tracking-[0.24em] text-[#14B8A6] uppercase">// 03 / {t.kicker}</div>
            <h2 className="font-display font-medium text-3xl lg:text-5xl text-gray-900 dark:text-white tracking-tight leading-[1.05] text-balance">{t.title}</h2>
          </div>
          <div className="lg:col-span-5">
            <p className="text-sm text-gray-500 dark:text-gray-400 leading-relaxed">{t.sub}</p>
          </div>
        </div>

        {/* Search */}
        <div className="relative mb-5">
          <IP.Search size={16} className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400"/>
          <input value={search} onChange={(e)=>setSearch(e.target.value)} placeholder={t.searchPlaceholder}
            className="w-full pl-11 pr-4 py-4 rounded-xl bg-white dark:bg-[#11182B] border border-gray-200 dark:border-white/10 text-[14px] text-gray-900 dark:text-white placeholder:text-gray-400 focus:border-[#14B8A6] outline-none transition-colors"/>
        </div>

        {/* Category filters */}
        <div className="flex flex-wrap items-center gap-2 mb-4">
          {t.cats.map(c=>{
            const Icon = IP[c.icon] || IP.Layers3;
            const on = cat===c.id;
            const count = c.id==='all' ? services.length : services.filter(s=>s.category===c.id).length;
            return (
              <button key={c.id} onClick={()=>{ setCat(c.id); setSubcat('all'); }} className={`group flex items-center gap-2 px-4 py-2.5 rounded-full text-[11px] font-medium tracking-[0.16em] uppercase transition-colors ${
                on
                  ? 'bg-[#14B8A6] text-white'
                  : 'bg-white dark:bg-[#11182B] text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-white/10 hover:border-[#14B8A6] hover:text-[#14B8A6]'
              }`}>
                <Icon size={13} className={on?'text-white':'text-[#14B8A6]'}/>
                {c.label}
                <span className={`font-mono text-[9px] ${on?'text-white/70':'text-gray-400'}`}>{count}</span>
              </button>
            );
          })}
        </div>

        {/* Subcategory filters */}
        {subOptions.length > 0 && (
          <div className="flex flex-wrap items-center gap-2 mb-8 pl-1">
            <button onClick={()=>setSubcat('all')} className={`px-3.5 py-1.5 rounded-full text-[11px] font-medium tracking-wide transition-colors ${
              subcat==='all' ? 'bg-gray-900 dark:bg-white text-white dark:text-[#0A0F1A]' : 'text-gray-500 dark:text-gray-400 border border-gray-300 dark:border-white/10 hover:border-[#14B8A6] hover:text-[#14B8A6]'
            }`}>{t.allSubcat}</button>
            {subOptions.map(sc=>(
              <button key={sc.id} onClick={()=>setSubcat(sc.id)} className={`px-3.5 py-1.5 rounded-full text-[11px] font-medium tracking-wide transition-colors ${
                subcat===sc.id ? 'bg-gray-900 dark:bg-white text-white dark:text-[#0A0F1A]' : 'text-gray-500 dark:text-gray-400 border border-gray-300 dark:border-white/10 hover:border-[#14B8A6] hover:text-[#14B8A6]'
              }`}>{sc.label}</button>
            ))}
          </div>
        )}

        {/* Results bar */}
        <div className="flex items-center justify-between mb-6 pb-4 border-b border-gray-200 dark:border-white/10">
          <span className="font-mono text-[10px] tracking-widest uppercase text-gray-500 dark:text-gray-400">
            {filtered.length} {t.resultsLabel}
          </span>
          {hasFilters && (
            <button onClick={clearFilters} className="inline-flex items-center gap-1.5 font-mono text-[10px] tracking-widest uppercase text-[#EF4444] hover:underline">
              <IP.X size={11}/>{t.clearFilters}
            </button>
          )}
        </div>

        {/* Grid / empty state */}
        {visible.length === 0 ? (
          <div className="text-center py-20 border border-dashed border-gray-300 dark:border-white/10 rounded-2xl">
            <IP.Search size={28} className="mx-auto text-gray-300 dark:text-gray-600 mb-4"/>
            <h3 className="font-display font-medium text-lg text-gray-900 dark:text-white mb-2">{t.noResultsTitle}</h3>
            <p className="text-sm text-gray-500 dark:text-gray-400 mb-5">{t.noResultsHint}</p>
            {hasFilters && (
              <button onClick={clearFilters} className="inline-flex items-center gap-2 font-mono text-[11px] uppercase tracking-widest text-[#14B8A6] hover:underline">
                <IP.X size={12}/>{t.clearFilters}
              </button>
            )}
          </div>
        ) : (
          <div className="grid sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-5">
            {visible.map(s=>(
              <ServiceCard key={s.id} s={s} lang={lang} catLabel={catLabel(s.category)} subLabel={subLabel(s)}
                inCart={cart.includes(s.id)} onOpen={setDetailId}/>
            ))}
          </div>
        )}

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="flex items-center justify-center gap-3 mt-10">
            <button onClick={()=>setPage(p=>Math.max(0,p-1))} disabled={safePage===0}
              className="w-10 h-10 rounded-full border border-gray-300 dark:border-white/15 text-gray-700 dark:text-gray-300 flex items-center justify-center hover:border-[#14B8A6] hover:text-[#14B8A6] disabled:opacity-30 disabled:cursor-not-allowed transition-colors">
              <IP.ArrowLeft size={15}/>
            </button>
            <span className="font-mono text-[10px] tracking-widest text-gray-500 dark:text-gray-400">
              {safePage+1} / {totalPages}
            </span>
            <button onClick={()=>setPage(p=>Math.min(totalPages-1,p+1))} disabled={safePage>=totalPages-1}
              className="w-10 h-10 rounded-full border border-gray-300 dark:border-white/15 text-gray-700 dark:text-gray-300 flex items-center justify-center hover:border-[#14B8A6] hover:text-[#14B8A6] disabled:opacity-30 disabled:cursor-not-allowed transition-colors">
              <IP.ArrowRight size={15}/>
            </button>
          </div>
        )}
      </div>

      {detailId && <ServiceDetailPanel id={detailId} onClose={()=>setDetailId(null)}/>}
    </section>
  );
}

Object.assign(window, { Portfolio, ServiceCard, ServiceDetailPanel });
