/* global React, ChIcon, NavIcon, CHANNELS */

const { useState: useStateR, useMemo: useMemoR } = React;

// ============ Data ============

const RESOLVED_TICKETS = [
  { id:"CNL-2841", channel:"whatsapp", customer:"María F. Soto",       company:"Distribuidora El Quetzal", printer:"HP LaserJet Pro M404dn", issue:"Atasco bandeja 2 · visita agendada", solver:"sofia", duration:"3:42", time:"10:46", kb:"KB-HP-M404-008" },
  { id:"CNL-2835", channel:"whatsapp", customer:"José Alvarado",       company:"Ferretería Alvarado",      printer:"HP LaserJet M111w",       issue:"Configuración WiFi resuelta vía KB",  solver:"sofia", duration:"4:08", time:"10:18", kb:"KB-HP-WIFI-002" },
  { id:"CNL-2826", channel:"call",     customer:"Hugo Méndez",         company:"Distribuciones HM",        printer:"HP Color LaserJet M283fdw", issue:"Reinicio tras corte eléctrico",      solver:"sofia", duration:"5:02", time:"09:31", kb:"KB-HP-RESET-004" },
  { id:"CNL-2824", channel:"web",      customer:"Andrea Pérez",        company:"Estética Andrea",          printer:"HP LaserJet M111w",       issue:"Descarga driver Windows 11",           solver:"sofia", duration:"3:18", time:"09:22", kb:"KB-HP-DRV-019" },
  { id:"CNL-2822", channel:"email",    customer:"Inversiones del Sur", company:"Inversiones del Sur",      printer:"HP OfficeJet Pro 9015e",  issue:"Solicitud de toner negro · despachado",solver:"sofia", duration:"8:11", time:"09:08", kb:"KB-HP-TONER-005" },
  { id:"CNL-2820", channel:"whatsapp", customer:"Carlos Aguilar",      company:"Carrocería Aguilar",       printer:"HP LaserJet Pro M404dn", issue:"Calidad: limpieza tambor de imagen",    solver:"sofia", duration:"7:44", time:"08:54", kb:"KB-HP-M428-021" },
  { id:"CNL-2818", channel:"call",     customer:"Sandra Villatoro",    company:"Clínica Villatoro",        printer:"Canon imageRUNNER 2625i", issue:"Error E000 · ciclo de fusor",          solver:"taller", duration:"42:18", time:"08:40", kb:"KB-CAN-IR2630-014" },
  { id:"CNL-2816", channel:"web",      customer:"Lucia Marroquín",     company:"Editorial Páginas",        printer:"HP LaserJet M428fdw",     issue:"Líneas verticales · cambio tambor",    solver:"dispatch", duration:"on-site", time:"08:22", kb:"KB-HP-M428-021" },
  { id:"CNL-2814", channel:"whatsapp", customer:"Ricardo Solís",       company:"Cafetería La Plaza",       printer:"HP LaserJet Pro M404n",   issue:"Conexión a red por WiFi",              solver:"sofia", duration:"4:55", time:"08:11", kb:"KB-HP-WIFI-002" },
  { id:"CNL-2812", channel:"email",    customer:"Yésica Tobar",        company:"Asoc. Mujeres Activas",    printer:"HP LaserJet Pro M404dn", issue:"Atasco · visita confirmada",            solver:"sofia", duration:"11:04", time:"07:58", kb:"KB-HP-M404-008" },
  { id:"CNL-2810", channel:"call",     customer:"Banca Crédito GT",    company:"Banca Crédito GT (sucursal Mixco)", printer:"Canon imageRUNNER 2630i", issue:"Reposición de papel · usuario nuevo", solver:"sofia", duration:"2:08", time:"07:42", kb:"KB-CAN-IR-OP-002" },
];

const TOP_KB = [
  { code: "KB-HP-M404-008", title: "Reemplazo rodillo bandeja 2", uses: 9, pct: 100 },
  { code: "KB-HP-M428-021", title: "Líneas verticales · tambor", uses: 7, pct: 78 },
  { code: "KB-HP-WIFI-002", title: "Configuración WiFi M111w", uses: 6, pct: 67 },
  { code: "KB-HP-TONER-005",title: "Sustitución cartucho amarillo", uses: 5, pct: 56 },
  { code: "KB-CAN-IR2630-014", title: "Códigos E000/E007", uses: 4, pct: 44 },
];

const TOP_MODELS = [
  { name: "HP LaserJet Pro M404dn", count: 14, pct: 100 },
  { name: "HP LaserJet M428fdw",     count: 9,  pct: 64 },
  { name: "HP LaserJet M111w",       count: 6,  pct: 43 },
  { name: "HP Color LaserJet M283fdw", count: 5, pct: 36 },
  { name: "Canon imageRUNNER 2630i", count: 4,  pct: 29 },
];

// hour distribution (00–23). Real ops hours have spikes
const HOURLY = [
  0,0,0,0,0,0,1,3,7,9,8,11,6,5,4,2,1,0,0,0,0,0,0,0
];

// ============ Components ============

const HourChart = ({ data }) => {
  const max = Math.max(1, ...data);
  return (
    <div className="hour-chart">
      <div className="hour-bars" style={{height:140}}>
        {data.map((v, h) => (
          <div key={h} className={`col ${v === max ? "peak" : ""}`}>
            <span className="vv">{v}</span>
            <i style={{height: v === 0 ? "2px" : `${(v / max) * 110}px`, opacity: v === 0 ? 0.18 : 1}}/>
            <span className="lh">{h % 2 === 0 ? String(h).padStart(2,"0") : ""}</span>
          </div>
        ))}
      </div>
      <p style={{margin:"12px 0 0",fontSize:11,color:"var(--text-3)",lineHeight:1.45}}>
        Pico de resolución entre <b style={{color:"var(--orange-deep)",fontFamily:"var(--mono)"}}>09:00–12:00</b> · coincide con apertura comercial. La cola post-almuerzo se aplana porque SOF.IA absorbe los pedidos repetidos sin escalar.
      </p>
    </div>
  );
};

const SOLVER_META = {
  sofia: { label: "SOF.IA", cls: "", avatar: "S", isSofia: true },
  dispatch: { label: "Dispatcher", cls: "manual", avatar: "OP", isSofia: false },
  taller: { label: "Taller", cls: "manual", avatar: "T", isSofia: false },
  conectividad: { label: "Conectividad", cls: "manual", avatar: "C", isSofia: false },
};

const ResolvedScreen = ({ openTicket }) => {
  const [solverFilter, setSolverFilter] = useStateR("all");
  const [chFilter, setChFilter] = useStateR("all");

  const filtered = useMemoR(() => {
    return RESOLVED_TICKETS.filter(t =>
      (solverFilter === "all" || t.solver === solverFilter) &&
      (chFilter === "all" || t.channel === chFilter)
    );
  }, [solverFilter, chFilter]);

  // totals derived from the source array (47 reflects the whole day, list shows recent)
  const TOTAL = 47;
  const SOFIA = 38;
  const HUMAN = 9;
  const sofiaPct = Math.round(SOFIA / TOTAL * 100);

  return (
    <div className="page" data-screen-label="08 Resueltos hoy">
      <div className="crumb"><a>Bandeja</a><span className="sep">/</span><a>Resueltos hoy</a></div>
      <div className="page-head">
        <div>
          <h1 className="page-title">Resueltos hoy</h1>
          <div className="page-sub">Resumen del día · 27 may 2026</div>
        </div>
        <div style={{display:"flex",gap:8}}>
          <button className="btn"><NavIcon name="history"/> Comparar con ayer</button>
          <button className="btn"><NavIcon name="metrics"/> Exportar reporte</button>
        </div>
      </div>

      {/* Hero */}
      <div className="rh-hero">
        <div className="lead">
          <h2><b>{SOFIA} de {TOTAL}</b> tickets resueltos por SOF.IA sin tocar a un humano.</h2>
          <p>Equivale a <b>{sofiaPct}% de resolución autónoma</b>. Tiempo medio de captura: 42 segundos. El equipo de Canella ganó cerca de <b>9 horas-persona</b> de tiempo operativo hoy.</p>
          <div className="date">27 may 2026 · 16:24 hrs · datos en vivo</div>
        </div>
        <div className="rh-kpi">
          <div className="l">Total cerrados</div>
          <div className="v">{TOTAL}<span className="u">tickets</span></div>
          <div className="d">▲ 6 vs. ayer</div>
        </div>
        <div className="rh-kpi">
          <div className="l">Por SOF.IA</div>
          <div className="v accent">{SOFIA}<span className="u">/ {TOTAL}</span></div>
          <div className="d">{sofiaPct}% autónomos</div>
        </div>
        <div className="rh-kpi">
          <div className="l">Tiempo medio</div>
          <div className="v">5<span className="u">min 14s</span></div>
          <div className="d">▼ 38s vs. ayer</div>
        </div>
        <div className="rh-kpi">
          <div className="l">Tiempo ahorrado</div>
          <div className="v success">8.7<span className="u">h-persona</span></div>
          <div className="d">≈ 1 jornada completa</div>
        </div>
      </div>

      {/* Celebrate strip */}
      <div className="celebrate">
        <div className="ic">★</div>
        <div style={{flex:1}}>
          <b>Récord del día · SOF.IA cerró un atasco HP M404 en 3 min 42 s</b>
          <p>Caso CNL-2841 (Distribuidora El Quetzal) · serie pronunciada en lenguaje natural, parseada y validada sin intervención humana. Material listo para entrenamiento de futuros casos.</p>
        </div>
        <button className="btn sm" style={{background:"rgba(255,255,255,0.18)",color:"#FFFFFF",borderColor:"rgba(255,255,255,0.3)"}} onClick={() => openTicket({id:"CNL-2841", channel:"whatsapp", state:"auto"})}>Ver caso →</button>
      </div>

      {/* Filters */}
      <div className="lc-toolbar">
        <div className="group">
          <span className="lbl">Resuelto por</span>
          {["all","sofia","dispatch","taller","conectividad"].map(o => (
            <span key={o} className={`seg ${solverFilter === o ? "on" : ""}`} onClick={() => setSolverFilter(o)}>
              {o === "all" ? "Todos" : SOLVER_META[o].label}
            </span>
          ))}
        </div>
        <div className="group">
          <span className="lbl">Canal</span>
          <span className={`seg ${chFilter === "all" ? "on" : ""}`} onClick={() => setChFilter("all")}>Todos</span>
          {CHANNELS.map(c => (
            <span key={c.id} className={`seg ${chFilter === c.id ? "on" : ""}`} onClick={() => setChFilter(c.id)}>
              {c.label.slice(0,4)}
            </span>
          ))}
        </div>
        <div style={{flex:1}}/>
        <span className="hint">{filtered.length} de {RESOLVED_TICKETS.length} mostrados · resto en histórico</span>
      </div>

      <div className="rh-grid">
        {/* List */}
        <div className="queue">
          <div className="q-head" style={{gridTemplateColumns:"32px 84px 1.2fr 1.3fr 0.9fr 110px 70px 32px"}}>
            <span></span>
            <span>Ticket</span>
            <span>Cliente</span>
            <span>Resolución</span>
            <span>Resuelto por</span>
            <span style={{textAlign:"right"}}>Duración</span>
            <span style={{textAlign:"right"}}>Cerrado</span>
            <span></span>
          </div>
          {filtered.map(t => {
            const meta = SOLVER_META[t.solver];
            const isLong = t.duration.includes(":") && parseInt(t.duration) > 20;
            const isManual = !meta.isSofia;
            return (
              <div
                key={t.id}
                className="q-row resolved"
                style={{gridTemplateColumns:"32px 84px 1.2fr 1.3fr 0.9fr 110px 70px 32px"}}
                onClick={() => openTicket({id: t.id, channel: t.channel, state: "auto"})}
              >
                <ChIcon channel={t.channel}/>
                <div className="id">#{t.id}</div>
                <div className="cust">
                  <b>{t.customer}</b>
                  <span>{t.company}</span>
                </div>
                <div>
                  <div style={{fontSize:12,color:"var(--text)",lineHeight:1.35}}>{t.issue}</div>
                  <div style={{fontFamily:"var(--mono)",fontSize:10,color:"var(--text-3)",marginTop:3,letterSpacing:"0.04em"}}>
                    {t.printer} · KB {t.kb}
                  </div>
                </div>
                <div className="handler">
                  <div className={`handler-avatar ${meta.isSofia ? "sofia" : ""}`}>{meta.avatar}</div>
                  <span>{meta.label}</span>
                </div>
                <div style={{textAlign:"right"}}>
                  <span className={`dur-pill ${isManual ? "manual" : isLong ? "slow" : ""}`}>
                    {t.duration === "on-site" ? "on-site" : t.duration}
                  </span>
                </div>
                <div className="time" style={{textAlign:"right"}}>{t.time}</div>
                <div className="arr"><NavIcon name="arrow"/></div>
              </div>
            );
          })}
          {filtered.length === 0 && (
            <div style={{padding:30,textAlign:"center",color:"var(--text-3)",fontSize:12,fontFamily:"var(--mono)",letterSpacing:"0.06em",textTransform:"uppercase"}}>
              — sin tickets con esos filtros —
            </div>
          )}
        </div>

        {/* Side */}
        <div className="rh-aside">
          <div className="kb-card">
            <div className="card-head">
              <NavIcon name="metrics"/>
              <h3>Distribución por hora</h3>
              <span className="tag">resueltos / hora</span>
            </div>
            <HourChart data={HOURLY}/>
          </div>

          <div className="kb-card">
            <div className="card-head">
              <NavIcon name="kb"/>
              <h3>KB más usadas hoy</h3>
              <span className="tag">top 5</span>
            </div>
            <div className="tops-list">
              {TOP_KB.map((k, i) => (
                <div key={k.code} className="tops-row">
                  <span className="nn">{String(i+1).padStart(2,"0")}</span>
                  <div className="nm">{k.title}<span className="sub">{k.code}</span></div>
                  <span className="bar"><i style={{width:`${k.pct}%`}}/></span>
                  <span className="ct">{k.uses}</span>
                </div>
              ))}
            </div>
          </div>

          <div className="kb-card">
            <div className="card-head">
              <NavIcon name="bookmark"/>
              <h3>Modelos atendidos</h3>
              <span className="tag">top 5</span>
            </div>
            <div className="tops-list">
              {TOP_MODELS.map((m, i) => (
                <div key={m.name} className="tops-row">
                  <span className="nn">{String(i+1).padStart(2,"0")}</span>
                  <div className="nm">{m.name}</div>
                  <span className="bar"><i style={{width:`${m.pct}%`}}/></span>
                  <span className="ct">{m.count}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

window.ResolvedScreen = ResolvedScreen;
