/* ============================================================
   dossier.jsx — live strategic profile that builds from answers
   ============================================================ */

/* tiny inline icons */
const Ic = {
  target: <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4"><circle cx="8" cy="8" r="6.2"/><circle cx="8" cy="8" r="3"/><circle cx="8" cy="8" r="0.4" fill="currentColor"/></svg>,
  tag: <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4"><path d="M2.5 8.5 8 3h4.5V7.5L7 13z"/><circle cx="10" cy="6" r="0.8" fill="currentColor"/></svg>,
  user: <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4"><circle cx="8" cy="5.5" r="2.6"/><path d="M3.2 13c0-2.6 2.1-4.2 4.8-4.2S12.8 10.4 12.8 13"/></svg>,
  star: <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4"><path d="M8 2.5l1.7 3.5 3.8.5-2.8 2.7.7 3.8L8 11.4 4.6 13.3l.7-3.8L2.5 6.8l3.8-.5z"/></svg>,
  funnel: <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4"><path d="M2.5 3h11l-4 5v4l-3 1.5V8z"/></svg>,
  broadcast: <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4"><circle cx="8" cy="8" r="1.6"/><path d="M5 5a4 4 0 000 6M11 5a4 4 0 010 6M3 3a7 7 0 000 10M13 3a7 7 0 010 10"/></svg>,
  spark: <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4"><path d="M8 2v3M8 11v3M2 8h3M11 8h3M4.2 4.2l2 2M9.8 9.8l2 2M11.8 4.2l-2 2M6.2 9.8l-2 2"/></svg>,
  key: <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4"><circle cx="5.5" cy="6" r="2.8"/><path d="M7.5 7.5L13 13M11 11l1.5-1.5M10 10l1.5-1.5"/></svg>,
  alert: <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4"><path d="M8 2.5L14 13H2z"/><path d="M8 6.5v3M8 11.3v.2"/></svg>,
};

function trunc(s, n) { s = String(s || "").trim(); return s.length > n ? s.slice(0, n).trim() + "…" : s; }

function ICard({ icon, label, children }) {
  return (
    <div className="icard">
      <div className="icard-l">{icon}{label}</div>
      {children}
    </div>
  );
}

function ReadinessRing({ pct }) {
  const r = 22, c = 2 * Math.PI * r;
  const off = c * (1 - pct / 100);
  return (
    <div className="meter-ring">
      <svg width="52" height="52" viewBox="0 0 52 52">
        <circle cx="26" cy="26" r={r} fill="none" stroke="rgba(243,236,214,0.14)" strokeWidth="4" />
        <circle cx="26" cy="26" r={r} fill="none" stroke="#DA8A64" strokeWidth="4" strokeLinecap="round"
          strokeDasharray={c} strokeDashoffset={off} style={{ transition: "stroke-dashoffset .7s cubic-bezier(.22,1,.36,1)" }} />
      </svg>
      <span className="pct">{pct}%</span>
    </div>
  );
}

function Dossier({ answers, stepId }) {
  const a = answers;
  const pct = computeProgress(a);
  const name = a.nome_empresa && a.nome_empresa.trim();
  const metaBits = [a.cidade, a.responsavel].filter(window.has);
  const channels = recommendChannels(a);
  const angles = creativeAngles(a);
  const pend = pendingAccess(a);
  const acCount = a.acessos ? Object.keys(a.acessos).length : 0;

  const readyLabel =
    pct < 25 ? "Coletando dados" : pct < 55 ? "Tomando forma" : pct < 85 ? "Quase lá" : "Pronto pra estratégia";

  const cards = [];

  if (window.has(a.objetivo))
    cards.push(
      <ICard key="foco" icon={Ic.target} label="Foco da campanha">
        <div className="minichips">
          {arr(a.objetivo).map((o) => <span key={o} className="minichip">{o}</span>)}
        </div>
        {a.meta_num && <div className="icard-v" style={{ marginTop: 10, fontSize: 13, color: "var(--cream-soft)" }}>Meta: {trunc(a.meta_num, 60)}</div>}
      </ICard>
    );

  if (window.has(a.produto))
    cards.push(
      <ICard key="oferta" icon={Ic.tag} label="Oferta">
        <div className="icard-v serif">{trunc(a.produto, 90)}</div>
        {Number(a.ticket) > 0 && <div className="minichips"><span className="minichip">Ticket: {formatBRL(a.ticket)}</span></div>}
      </ICard>
    );

  if (window.has(a.cliente_ideal))
    cards.push(
      <ICard key="pub" icon={Ic.user} label="Público ideal">
        <div className="icard-v" style={{ fontSize: 13.5, color: "var(--cream-soft)" }}>{trunc(a.cliente_ideal, 110)}</div>
        {(arr(a.idade).length || a.renda) && (
          <div className="minichips">
            {arr(a.idade).map((i) => <span key={i} className="minichip">{i}</span>)}
            {a.renda && <span className="minichip">{a.renda}</span>}
          </div>
        )}
      </ICard>
    );

  if (window.has(a.diferenciais))
    cards.push(
      <ICard key="dif" icon={Ic.star} label="Diferencial">
        <div className="icard-v" style={{ fontSize: 13.5, color: "var(--cream-soft)" }}>{trunc(a.diferenciais, 100)}</div>
        {arr(a.provas).length > 0 && (
          <div className="minichips">{arr(a.provas).map((p) => <span key={p} className="minichip">{p}</span>)}</div>
        )}
      </ICard>
    );

  if (window.has(a.destino))
    cards.push(
      <ICard key="funil" icon={Ic.funnel} label="Funil">
        <div className="minichips">{arr(a.destino).map((d) => <span key={d} className="minichip">{d}</span>)}</div>
        {a.follow_up === "Não tem" && <div className="minichips"><span className="minichip warn">Sem follow-up</span></div>}
      </ICard>
    );

  /* derived intelligence — appears once enough is known */
  if (window.has(a.objetivo))
    cards.push(
      <ICard key="canais" icon={Ic.broadcast} label="Canais recomendados">
        <div className="minichips">{channels.map((c) => <span key={c.name} className="minichip rec">{c.name}</span>)}</div>
      </ICard>
    );

  if (window.has(a.diferenciais) || arr(a.provas).length)
    cards.push(
      <ICard key="angulos" icon={Ic.spark} label="Ângulos de criativo">
        <ul className="icard-list">
          {angles.slice(0, 4).map((x) => <li key={x}><span className="b">›</span>{x}</li>)}
        </ul>
      </ICard>
    );

  if (acCount > 0)
    cards.push(
      <ICard key="acessos" icon={Ic.key} label="Acessos">
        <div className="icard-v" style={{ fontSize: 14 }}>
          {acCount} mapeado{acCount > 1 ? "s" : ""}
          {pend.length > 0 && <span style={{ color: "var(--clay-soft)" }}> · {pend.length} pendente{pend.length > 1 ? "s" : ""}</span>}
        </div>
      </ICard>
    );

  if (pct >= 60 && attentionPoints(a).length && stepId !== "report")
    cards.push(
      <ICard key="aten" icon={Ic.alert} label="Ponto de atenção">
        <div className="icard-v" style={{ fontSize: 13.5, color: "var(--cream-soft)" }}>{trunc(attentionPoints(a)[0], 130)}</div>
      </ICard>
    );

  return (
    <aside className="dossier">
      <div className="dossier-head">
        <div className="dossier-tag"><span className="live" />Dossiê Estratégico · ao vivo</div>
        <h2 className="dossier-title">{name || "Novo cliente"}</h2>
        <div className="dossier-meta">{metaBits.length ? metaBits.join("  ·  ") : "Preencha pra montar o perfil →"}</div>
        <div className="meter">
          <ReadinessRing pct={pct} />
          <div className="meter-txt">
            <div className="m-l">Prontidão do diagnóstico</div>
            <div className="m-s">{readyLabel}</div>
          </div>
        </div>
      </div>

      <div className="dossier-body">
        {cards.length === 0 ? (
          <div className="dossier-empty">
            <svg className="di" viewBox="0 0 48 48" fill="none" stroke="currentColor" strokeWidth="1.3">
              <rect x="9" y="6" width="30" height="36" rx="3" />
              <path d="M15 15h18M15 22h18M15 29h12" />
            </svg>
            <p>Cada resposta sua vira um insight aqui. Vamos montando sua estratégia em tempo real.</p>
          </div>
        ) : cards}
      </div>
    </aside>
  );
}

Object.assign(window, { Dossier });
