/* global React, ChIcon, NavIcon, CHANNELS, StateBadge, FOCUSED_CASE, CASE_EMAIL, CASE_WEB, SUB_PHASES, EQUIPMENT_HISTORY, ATTACHMENTS_2841, SLA_2841, AUDIT_2841 */

// Resolve case by ticket id — falls back to FOCUSED_CASE
const CASE_MAP = {
  "CNL-2841": () => FOCUSED_CASE,
  "CNL-2836": () => CASE_EMAIL,
  "CNL-2838": () => CASE_WEB,
};

const getCase = (id) => (CASE_MAP[id] || (() => FOCUSED_CASE))();

// =========== Channel-specific conversation renderers ===========

const WaConversation = ({ messages }) => (
  <div className="conv-body cv-wa" style={{position:"relative"}}>
    {messages.map((m, i) => (
      <div key={i} className={`bubble-row ${m.dir}`}>
        <div className={`bubble ${m.dir}`}>
          <BubbleText text={m.text}/>
          <span className="time">{m.time} {m.dir === "out" && "✓✓"}</span>
        </div>
      </div>
    ))}
  </div>
);

const IgConversation = ({ messages }) => (
  <div className="conv-body cv-ig" style={{position:"relative"}}>
    {messages.map((m, i) => (
      <div key={i} className={`bubble-row ${m.dir}`}>
        <div className={`bubble ${m.dir}`}>
          <BubbleText text={m.text}/>
          <span className="time">{m.time}</span>
        </div>
      </div>
    ))}
  </div>
);

const FbConversation = ({ messages }) => (
  <div className="conv-body cv-fb" style={{position:"relative"}}>
    {messages.map((m, i) => (
      <div key={i} className={`bubble-row ${m.dir}`}>
        <div className={`bubble ${m.dir}`}>
          <BubbleText text={m.text}/>
          <span className="time">{m.time}</span>
        </div>
      </div>
    ))}
  </div>
);

const WebConversation = ({ messages, customer }) => (
  <div className="conv-body cv-web" style={{padding:0,position:"relative"}}>
    <div className="web-widget-head">
      <div style={{width:30,height:30,borderRadius:8,background:"rgba(255,255,255,0.18)",display:"grid",placeItems:"center",fontFamily:"var(--mono)",fontWeight:700,fontSize:12}}>S</div>
      <div style={{flex:1}}>
        <b>SOF.IA · Canella</b>
        <span>asistente · típicamente responde al instante</span>
      </div>
      <span style={{fontFamily:"var(--mono)",fontSize:10,opacity:0.85}}>● en línea</span>
    </div>
    <div style={{padding:20}}>
      {messages.map((m, i) => (
        <div key={i} className={`bubble-row ${m.dir}`}>
          <div className={`bubble ${m.dir}`}>
            <BubbleText text={m.text}/>
            <span className="time">{m.time}</span>
          </div>
        </div>
      ))}
    </div>
  </div>
);

const EmailConversation = ({ thread }) => (
  <div className="conv-body cv-email" style={{padding:0}}>
    <div className="email-thread">
      {thread.map((e, i) => (
        <div key={i} className={`email-msg ${e.isFormal ? "formal" : ""}`}>
          <div className="em-head">
            <div className={`em-avatar ${e.direction === "in" ? "in" : ""}`}>
              {e.direction === "in" ? "KE" : "S"}
            </div>
            <div className="em-from">
              <b>{e.fromName}</b>
              <span>{e.from}</span>
            </div>
            <div className="em-time">{e.time}</div>
          </div>
          <div className="em-subject">{e.subject}</div>
          <div className="em-to">
            <span><b style={{color:"var(--text-2)",fontWeight:500}}>Para:</b> {e.to}</span>
            {e.cc && <span><b style={{color:"var(--text-2)",fontWeight:500}}>CC:</b> {e.cc}</span>}
          </div>
          <div className="em-body">{e.body}</div>
          {e.hasAttachments && (
            <div className="em-att">
              <span className="pill">📎 display_error.jpg · 0.8 MB</span>
              <span className="pill">📎 atasco_papel.jpg · 1.2 MB</span>
            </div>
          )}
        </div>
      ))}
    </div>
  </div>
);

const ConversationByChannel = ({ c }) => {
  if (c.channel === "whatsapp") return <WaConversation messages={c.conversation}/>;
  if (c.channel === "web") return <WebConversation messages={c.conversation} customer={c.customer}/>;
  if (c.channel === "email") return <EmailConversation thread={c.emailThread}/>;
  return <WaConversation messages={c.conversation || []}/>;
};

const BubbleText = ({ text }) => (
  <div style={{whiteSpace:"pre-wrap"}}>
    {text.split("\n").map((line, i) => (
      <div key={i} dangerouslySetInnerHTML={{__html: line.replace(/\*([^*]+)\*/g,"<b>$1</b>")}}/>
    ))}
  </div>
);

// =========== Phase strip ===========
const PhaseStrip = ({ currentIdx }) => (
  <div className="phase-strip">
    <span className="label">Fase actual</span>
    {SUB_PHASES.map((p, i) => (
      <React.Fragment key={p}>
        <span className={`phase-pill ${i < currentIdx ? "done" : i === currentIdx ? "current" : ""}`}>
          {i < currentIdx && <span className="ck">✓</span>}
          {p}
        </span>
        {i < SUB_PHASES.length - 1 && <span className="phase-arrow">→</span>}
      </React.Fragment>
    ))}
  </div>
);

// =========== Equipment history card ===========
const HistoryCard = ({ serial }) => {
  const eq = EQUIPMENT_HISTORY[serial];
  if (!eq) return null;
  return (
    <div className="kb-card">
      <div className="card-head">
        <NavIcon name="history"/>
        <h3>Historial del equipo</h3>
        <span className="tag">{eq.pastTickets.length} tickets previos · SN {serial}</span>
      </div>
      <div className="equipment-card">
        <div className="stats">
          <div className="st"><div className="l">Instalado</div><div className="v">{eq.installed}</div></div>
          <div className="st"><div className="l">Contador</div><div className="v" style={{fontFamily:"var(--mono)"}}>{eq.counter.toLocaleString()}</div></div>
          <div className="st"><div className="l">Promedio mensual</div><div className="v" style={{fontFamily:"var(--mono)"}}>{eq.avgMonthly.toLocaleString()}</div></div>
        </div>
        {eq.alerts.map((a, i) => (
          <div key={i} className="alert">
            <span style={{flexShrink:0}}>⚠</span>
            <span>{a}</span>
          </div>
        ))}
      </div>
      <div className="history-list">
        {eq.pastTickets.map(t => (
          <div key={t.id} className="hist-row">
            <span className="date">{t.date}</span>
            <ChIcon channel={t.channel} size="sm"/>
            <div>
              <div className="issue">{t.issue}</div>
              <div className="solver">#{t.id} · {t.solver} · {t.duration}</div>
            </div>
            <button className="btn sm ghost">Ver</button>
          </div>
        ))}
      </div>
    </div>
  );
};

// =========== Attachments ===========
const AttachmentsCard = () => (
  <div className="kb-card">
    <div className="card-head">
      <NavIcon name="bookmark"/>
      <h3>Adjuntos del cliente</h3>
      <span className="tag">{ATTACHMENTS_2841.length} archivos</span>
    </div>
    <div className="attachments">
      {ATTACHMENTS_2841.map((a, i) => (
        <div key={i} className="att-thumb">
          {a.kind === "image" && (
            <div className="att-img-ph">
              <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
                <rect x="3" y="3" width="18" height="18" rx="2"/>
                <circle cx="8.5" cy="8.5" r="1.5"/>
                <path d="m21 15-5-5L5 21"/>
              </svg>
            </div>
          )}
          {a.kind === "audio" && (
            <div className="att-audio-ph">
              {Array.from({length:18}).map((_,k) => <i key={k} style={{height:`${10 + (k%5)*8}px`,opacity:0.45 + (k%5)*0.12}}/>)}
            </div>
          )}
          <div className="att-meta">
            <b>{a.label}</b>
            <span>
              <ChIcon channel={a.source} size="sm"/>
              {a.time} · {a.size}
            </span>
          </div>
        </div>
      ))}
    </div>
  </div>
);

// =========== SLA card ===========
const SlaCard = () => (
  <div className="kb-card">
    <div className="card-head">
      <NavIcon name="pending"/>
      <h3>Línea de tiempo / SLA</h3>
      <span className="tag">{SLA_2841.target}</span>
    </div>
    <div className="sla-card">
      <div className="sla-summary">
        <div className="ico">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polyline points="20 6 9 17 4 12"/></svg>
        </div>
        <div style={{flex:1}}>
          <b>A tiempo · captura total {SLA_2841.totalCapture}</b>
          <p>Todos los segmentos dentro del objetivo. SOF.IA cerró el caso 3:42 después del primer mensaje.</p>
        </div>
        <span className="auto-badge">A TIEMPO</span>
      </div>
      <div className="sla-bar">
        {SLA_2841.segments.map((s, i) => (
          <div key={i} className="sla-seg">
            <div className="ph">{s.phase}</div>
            <div className="du">{s.duration}</div>
          </div>
        ))}
      </div>
    </div>
  </div>
);

// =========== Audit trail ===========
const AuditCard = () => (
  <div className="kb-card">
    <div className="card-head">
      <NavIcon name="history"/>
      <h3>Trazabilidad · auditoría</h3>
      <span className="tag">{AUDIT_2841.length} eventos · 100% auditable</span>
    </div>
    <div className="audit">
      {AUDIT_2841.map((row, i) => (
        <div key={i} className="audit-row">
          <span className="at">{row.time}</span>
          <span className={`ico ${row.actor === "sofia" ? "sofia" : row.actor === "system" ? "system" : "human"}`}>
            {row.actor === "sofia" ? "S" : row.actor === "system" ? "·" : "H"}
          </span>
          <div className="what">
            <b>{row.action}</b>
            <span>{row.note}</span>
          </div>
        </div>
      ))}
    </div>
  </div>
);

// =========== Reasoning timeline (existing) ===========
const Reasoning = ({ c }) => (
  <div className="kb-card">
    <div className="card-head">
      <div className="brand-mark" style={{width:22,height:22,fontSize:11,borderRadius:6}}>S</div>
      <h3>Registro de razonamiento de SOF.IA</h3>
      <span className="tag">{c.reasoning?.length || 0} pasos · 100% auto</span>
    </div>
    <div className="timeline">
      {(c.reasoning || []).map(step => (
        <div key={step.idx} className={`tl-step ${step.state}`}>
          <div className="dot">{step.idx}</div>
          <div className="body">
            <b>{step.title}</b>
            <p dangerouslySetInnerHTML={{__html: step.body.replace(/`([^`]+)`/g,"<code>$1</code>").replace(/\*\*([^*]+)\*\*/g,"<b style='color:var(--text)'>$1</b>").replace(/\*([^*]+)\*/g,"<i style='color:var(--text)'>$1</i>")}}/>
          </div>
          <div className="stamp">
            <span className="auto-badge">AUTO</span>
            {step.time}
          </div>
        </div>
      ))}
    </div>
  </div>
);

const KbHitsCard = ({ c }) => (
  c.kbHits ? (
    <div className="kb-card">
      <div className="card-head">
        <h3>Knowledge Base · consultada</h3>
        <span className="tag">{c.kbHits.length} resultados</span>
      </div>
      <div className="kb-hits">
        {c.kbHits.map((h, i) => (
          <div key={i} className="kb-hit">
            <div className="score">{h.score}</div>
            <div className="doc">
              <b>{h.title}</b>
              <p>{h.snippet}</p>
              <span>{h.section}</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  ) : null
);

// =========== Main case screen ===========
const CaseScreen = ({ ticketId, goToQueue, goToEscalation }) => {
  const c = getCase(ticketId || "CNL-2841");
  const channelMeta = CHANNELS.find(x => x.id === c.channel);
  const isFocused = c.id === "CNL-2841";
  const phaseIdx = isFocused ? 7 : c.channel === "email" ? 5 : 3;

  return (
    <div className="page" data-screen-label="02 Caso resuelto por SOF.IA">
      <div className="crumb">
        <a onClick={goToQueue} style={{cursor:"pointer"}}>← Bandeja</a>
        <span className="sep">/</span>
        <a>Tickets activos</a>
        <span className="sep">/</span>
        <a>#{c.id}</a>
      </div>

      <div className="page-head">
        <div>
          <h1 className="page-title">Ticket #{c.id} · {c.customer}</h1>
          <div className="page-sub">
            {c.state === "auto" ? "Resuelto por SOF.IA" : c.state === "progress" ? "En curso con SOF.IA" : "Caso escalado"}
            {" · captura "}{c.duration}{" · canal "}{channelMeta.label}
          </div>
        </div>
        <div style={{display:"flex",gap:8}}>
          <button className="btn" onClick={goToQueue}>← Volver a la cola</button>
          <button className="btn danger" onClick={goToEscalation}>⚠ Tomar control / Override humano</button>
        </div>
      </div>

      <PhaseStrip currentIdx={phaseIdx}/>

      {/* Context strip */}
      <div className="case-context">
        <div className="ctx-cell">
          <div className="label">Canal de origen</div>
          <div className="value" style={{display:"flex",alignItems:"center",gap:8,marginTop:4}}>
            <ChIcon channel={c.channel} size="sm"/> {channelMeta.label}
          </div>
        </div>
        <div className="ctx-cell">
          <div className="label">Cliente</div>
          <div className="value">{c.customer}</div>
          <div className="sub">{c.company}</div>
        </div>
        <div className="ctx-cell">
          <div className="label">Equipo</div>
          <div className="value">{c.printer}</div>
          <div className="sub">SN · {c.serial}</div>
        </div>
        <div className="ctx-cell">
          <div className="label">Contrato</div>
          <div className="value mono">{c.contract}</div>
        </div>
        <div className="ctx-cell">
          <div className="label">Resultado</div>
          <div className="value" style={{display:"flex",alignItems:"center",gap:8,marginTop:4}}>
            <StateBadge state={c.state}/>
          </div>
          <div className="sub">
            {c.channel === "email" ? "visita técnica miércoles" :
             c.channel === "web" ? "consumible despachado" :
             "visita técnica agendada"}
          </div>
        </div>
      </div>

      <div className="case">
        {/* LEFT — conversation */}
        <div className="conv-panel">
          <div className="conv-head">
            <ChIcon channel={c.channel} size="lg"/>
            <div className="who">
              <b>{c.customer}</b>
              <span>{c.customerSub} · vía {channelMeta.label}</span>
            </div>
            <span className="hint">{c.startedAt || ""}</span>
          </div>
          <ConversationByChannel c={c}/>
          <div className="action-bar">
            <button className="btn"><NavIcon name="user"/> Reasignar canal</button>
            <button className="btn"><NavIcon name="bookmark"/> Guardar como ejemplo</button>
            <div className="grow"/>
            <span className="hint">{c.state === "auto" ? "SOF.IA cerró la conversación" : "Conversación en curso"}</span>
          </div>
        </div>

        {/* RIGHT — reasoning + KB hits */}
        <div className="reason">
          {c.reasoning ? <Reasoning c={c}/> : (
            <div className="kb-card" style={{padding:"24px 22px",fontSize:13,color:"var(--text-2)",lineHeight:1.6}}>
              <b style={{display:"block",color:"var(--text)",marginBottom:6}}>Razonamiento en curso</b>
              SOF.IA está procesando este caso. El registro completo aparece cuando se cierra el ticket o se escala. Aún {c.duration} de captura · indagando falla.
            </div>
          )}
          <KbHitsCard c={c}/>
        </div>
      </div>

      {/* Enrichments only for the fully-fleshed focused case */}
      {isFocused && (
        <>
          <div className="case-aux">
            <HistoryCard serial={c.serial}/>
            <AttachmentsCard/>
          </div>
          <div className="case-aux cols-1" style={{marginTop:0}}>
            <SlaCard/>
          </div>
          <div className="case-aux cols-1" style={{marginTop:0}}>
            <AuditCard/>
          </div>

          {/* Email panel */}
          <div className="kb-card" style={{marginTop:18}}>
            <div className="card-head">
              <NavIcon name="bolt"/>
              <h3>Correo redactado por SOF.IA</h3>
              <span className="tag">Enviado automáticamente · 10:46</span>
              <div style={{marginLeft:"auto",display:"flex",gap:8}}>
                <button className="btn sm">Ver hilo completo</button>
                <button className="btn sm primary">Reenviar</button>
              </div>
            </div>
            <div className="email-card" style={{margin:18}}>
              <div className="email-meta">
                <b>Para:</b><span>{c.email.to}</span>
                <b>CC:</b><span>{c.email.cc}</span>
                <b>Asunto:</b><span style={{color:"var(--text)"}}>{c.email.subject}</span>
              </div>
              <div className="email-body">{c.email.body}</div>
            </div>
          </div>

          {/* Star case callout */}
          <div className="kb-card" style={{marginTop:18, borderColor:"rgba(255,92,0,0.3)", background:"radial-gradient(600px 200px at 90% 0%, var(--orange-bg), transparent 60%), #FFFFFF"}}>
            <div className="card-head" style={{borderColor:"rgba(255,92,0,0.2)"}}>
              <div className="brand-mark" style={{width:22,height:22,fontSize:11,borderRadius:6}}>★</div>
              <h3 style={{color:"var(--orange-deep)"}}>Caso estrella · serie pronunciada de forma ambigua</h3>
              <span className="tag">Patrón #41 · HP M-series</span>
            </div>
            <div style={{padding:"16px 20px",fontSize:13,color:"var(--text-2)",lineHeight:1.6}}>
              La cliente dictó la serie como <code style={{fontFamily:"var(--mono)",background:"var(--orange-bg)",padding:"1px 6px",borderRadius:4,color:"var(--orange-deep)",border:"1px solid rgba(255,92,0,0.2)"}}>"VNB tres K uno dos cero ochenta y nueve"</code>. El parser de SOF.IA convirtió palabras a dígitos (ochenta y nueve → 89), normalizó separadores y validó el formato HP de 10 caracteres alfanuméricos. Cuando hubo coincidencia múltiple por los últimos 4 dígitos, verificó <b style={{color:"var(--text)"}}>nombre y dirección</b> contra la BD para desambiguar — sin pedir al cliente que volviera a deletrear. Tiempo total de captura: <b style={{color:"var(--orange-deep)",fontFamily:"var(--mono)"}}>11 segundos</b>.
            </div>
          </div>
        </>
      )}
    </div>
  );
};

window.CaseScreen = CaseScreen;
