/* global React, NavIcon, KB_ARTICLES, KB_SUGGESTIONS */

const { useState: useStateKB, useMemo: useMemoKB } = React;

const CATEGORIES = ["Todos","Mantenimiento HW","Diagnóstico","Calidad","Consumibles","Conectividad","Operación"];
const BRANDS = ["Todas","HP","Canon"];

const KbScreen = () => {
  const [cat, setCat] = useStateKB("Todos");
  const [brand, setBrand] = useStateKB("Todas");
  const [selected, setSelected] = useStateKB(KB_ARTICLES[0]);
  const [q, setQ] = useStateKB("");

  const filtered = useMemoKB(() => {
    return KB_ARTICLES.filter(a =>
      (cat === "Todos" || a.category === cat) &&
      (brand === "Todas" || a.brand === brand) &&
      (q === "" || (a.title + " " + a.code + " " + a.models.join(" ")).toLowerCase().includes(q.toLowerCase()))
    );
  }, [cat, brand, q]);

  const catCounts = useMemoKB(() => {
    const c = {};
    KB_ARTICLES.forEach(a => { c[a.category] = (c[a.category] || 0) + 1; });
    return c;
  }, []);

  return (
    <div className="page" data-screen-label="04 Knowledge Base">
      <div className="crumb"><a>SOF.IA</a><span className="sep">/</span><a>Knowledge Base</a></div>
      <div className="page-head">
        <div>
          <h1 className="page-title">Knowledge Base</h1>
          <div className="page-sub">{KB_ARTICLES.length} artículos · SOF.IA los consulta antes de proponer una solución</div>
        </div>
        <div style={{display:"flex",gap:8}}>
          <button className="btn"><NavIcon name="rotate"/> Sincronizar</button>
          <button className="btn primary"><NavIcon name="bolt"/> Nuevo artículo</button>
        </div>
      </div>

      {/* SOF.IA suggestions */}
      {KB_SUGGESTIONS.map((s, i) => (
        <div key={i} className="kb-suggest">
          <div className="icon"><NavIcon name="bolt"/></div>
          <div style={{flex:1}}>
            <b>SOF.IA detectó {s.cases} casos similares sin artículo · "{s.title}"</b>
            <p>{s.detail} <span style={{fontFamily:"var(--mono)",color:"var(--text-3)",marginLeft:6}}>· {s.period}</span></p>
          </div>
          <button className="btn primary sm">Crear KB</button>
          <button className="btn sm">Descartar</button>
        </div>
      ))}

      <div className="kb-layout">
        {/* Filters */}
        <aside className="kb-filters">
          <div style={{display:"flex",alignItems:"center",gap:8,background:"var(--bg-2)",border:"1px solid var(--line)",borderRadius:8,padding:"7px 10px",marginBottom:14}}>
            <NavIcon name="filter"/>
            <input
              value={q}
              onChange={e => setQ(e.target.value)}
              placeholder="Buscar código, modelo…"
              style={{flex:1,background:"none",border:"none",outline:"none",fontSize:12,color:"var(--text)",fontFamily:"var(--mono)"}}
            />
          </div>

          <h4>Categoría</h4>
          <div className="kb-filter-list">
            {CATEGORIES.map(c => (
              <label key={c} className={cat === c ? "on" : ""} onClick={() => setCat(c)}>
                {c}
                <span className="ct">{c === "Todos" ? KB_ARTICLES.length : (catCounts[c] || 0)}</span>
              </label>
            ))}
          </div>

          <h4>Marca</h4>
          <div className="kb-filter-list">
            {BRANDS.map(b => (
              <label key={b} className={brand === b ? "on" : ""} onClick={() => setBrand(b)}>
                {b}
                <span className="ct">{b === "Todas" ? KB_ARTICLES.length : KB_ARTICLES.filter(a => a.brand === b).length}</span>
              </label>
            ))}
          </div>

          <h4>Tipo de falla</h4>
          <div className="kb-filter-list">
            {["Atasco / arrastre","Calidad impresión","Consumibles","Conectividad","Fusor / temperatura"].map(t => (
              <label key={t}>{t}<span className="ct">{KB_ARTICLES.filter(a => a.faultType === t).length}</span></label>
            ))}
          </div>
        </aside>

        {/* List + Detail */}
        <div style={{display:"flex",flexDirection:"column",gap:18}}>
          <div className="kb-grid">
            {filtered.map(a => (
              <div
                key={a.code}
                className={`kb-card-item ${selected?.code === a.code ? "selected" : ""}`}
                onClick={() => setSelected(a)}
              >
                <div className="kb-code">{a.code}</div>
                <div className="kb-title">{a.title}</div>
                <div className="kb-models">{a.models.slice(0,2).join(" · ")}{a.models.length > 2 ? ` +${a.models.length-2}` : ""}</div>
                <div className="kb-stats">
                  <span className="stat"><b>{a.uses}</b>usos</span>
                  <span className={`stat ${a.successRate >= 0.9 ? "success" : ""}`}><b>{Math.round(a.successRate*100)}%</b>éxito</span>
                  <span style={{marginLeft:"auto"}}>{a.updated}</span>
                </div>
              </div>
            ))}
            {filtered.length === 0 && (
              <div style={{gridColumn:"1 / -1",padding:30,textAlign:"center",color:"var(--text-3)",fontSize:13}}>
                Sin resultados para los filtros activos.
              </div>
            )}
          </div>

          {/* Detail */}
          {selected && selected.steps && (
            <div className="kb-detail">
              <div className="kb-detail-head">
                <div className="kb-code">{selected.code}</div>
                <h2>{selected.title}</h2>
                <div className="meta">
                  <span><b>Categoría:</b> {selected.category}</span>
                  <span><b>Tipo de falla:</b> {selected.faultType}</span>
                  <span><b>Última actualización:</b> {selected.updated}</span>
                  <span><b>Autor:</b> {selected.author || "—"}</span>
                </div>
                <div className="kb-perf">
                  <div className="cell"><div className="l">Tickets resueltos</div><div className="v">{selected.uses}</div></div>
                  <div className="cell"><div className="l">Tasa de éxito</div><div className="v success">{Math.round(selected.successRate*100)}%</div></div>
                  <div className="cell"><div className="l">Tiempo medio app.</div><div className="v">3.8 <span style={{fontSize:12,color:"var(--text-3)",fontFamily:"var(--mono)"}}>min</span></div></div>
                </div>
              </div>

              <div className="kb-card" style={{margin:0}}>
                <div className="card-head">
                  <h3>Modelos compatibles</h3>
                </div>
                <div style={{padding:"12px 18px",display:"flex",gap:6,flexWrap:"wrap"}}>
                  {selected.models.map(m => (
                    <span key={m} className="k-pill" style={{fontSize:11}}>{m}</span>
                  ))}
                </div>
              </div>

              <div className="kb-card" style={{margin:0}}>
                <div className="card-head">
                  <h3>Procedimiento</h3>
                  <span className="tag">{selected.steps.length} pasos</span>
                </div>
                <div className="kb-steps">
                  {selected.steps.map((s, i) => (
                    <div key={i} className="kb-step">
                      <div className="n">{i+1}</div>
                      <div>{s}</div>
                    </div>
                  ))}
                </div>
              </div>

              {selected.parts && (
                <div className="kb-card" style={{margin:0,paddingBottom:8}}>
                  <div className="card-head">
                    <h3>Repuestos requeridos</h3>
                    <span className="tag">{selected.parts.length} items</span>
                  </div>
                  <div className="kb-parts-table">
                    <div className="row head"><div>Ref.</div><div>Descripción</div><div>Stock</div></div>
                    {selected.parts.map(p => (
                      <div key={p.ref} className="row">
                        <div className="ref">{p.ref}</div>
                        <div>{p.name}</div>
                        <div style={{fontFamily:"var(--mono)",color: p.stock < 5 ? "var(--red)" : "var(--green)"}}>{p.stock} u.</div>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}
          {selected && !selected.steps && (
            <div className="kb-card" style={{padding:"22px 24px",color:"var(--text-3)",fontSize:13}}>
              <b style={{color:"var(--text)",display:"block",marginBottom:6}}>{selected.title}</b>
              Selecciona un artículo de la lista superior para ver el procedimiento completo. Este artículo aún no tiene su contenido extendido cargado en la demo.
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

window.KbScreen = KbScreen;
