/* global React */
/* Cosidata Portal · diagnóstico data-driven por e-mail (onboarding_responses) */
const { useState: useStateDg, useEffect: useEffectDg } = React;

const DG_SUPABASE_URL     = "https://guydmkcqklluhfqtmvnx.supabase.co";
const DG_SUPABASE_ANON_KEY = "sb_publishable_zwjW1d7ey0myfWUj5lgQKA_osGdvTuY";

const DG_OND = {
  excel: "Excel / Google Sheets", erp: "Sistema ERP", crm: "CRM",
  sql: "Base SQL / Data Warehouse", arquivos: "Arquivos soltos (PDF, e-mail, WhatsApp)",
  naosabe: "Não sabe ao certo", outro: "Outro",
};
const DG_DASH  = { sim: "Sim", nao: "Ainda não", construindo: "Em construção" };
const DG_IA    = { sim: "Sim, ativamente", experimentei: "Experimentou, não usa", nao: "Ainda não" };
const DG_FIN   = { sim: "Estruturado", parcial: "Parcial", nao: "Não" };
const DG_BUD   = { ate50: "até 50", "50-150": "50–150", "150-500": "150–500", "500+": "+500", nd: "a definir" };
const DG_MOEDA = { BRL: "R$", EUR: "€", USD: "$" };
const DG_MAT   = {
  1: "Tudo no feeling", 2: "Quase tudo na intuição", 3: "Decisões mistas",
  4: "Bastante orientada a dados", 5: "100% orientada a dados",
};
const DG_TONE  = { green: "#16A085", amber: "#D9A400", red: "#D64545", muted: "#5F6175" };

async function fetchOnboardingRow(email, token) {
  const url = DG_SUPABASE_URL + "/rest/v1/onboarding_responses?select=*&email=eq." + encodeURIComponent(email);
  const headers = { apikey: DG_SUPABASE_ANON_KEY };
  if (token) headers.Authorization = "Bearer " + token;
  const res = await fetch(url, { headers });
  if (!res.ok) throw new Error("Supabase " + res.status + ": " + (await res.text().catch(() => "")));
  const rows = await res.json();
  return rows && rows.length ? rows[rows.length - 1] : null;
}

function normalizeOnboarding(r) {
  if (!r) return null;
  const onde = (r.onde_dados || []).map(k => k === "outro" ? (r.onde_dados_outro || "Outro") : (DG_OND[k] || k));
  const ferramentas = (r.ferramentas || "").split(",").map(s => s.trim()).filter(Boolean);
  const mat = Number(r.maturidade_dados) || 0;
  const status = [
    { label: "Dashboard de decisão", value: DG_DASH[r.usa_dashboard] || "–", tone: r.usa_dashboard === "sim" ? "green" : "muted" },
    { label: "Uso de IA", value: DG_IA[r.usa_ia] || "–", tone: r.usa_ia === "sim" ? "green" : r.usa_ia === "experimentei" ? "amber" : "muted" },
    { label: "Controle financeiro", value: DG_FIN[r.controle_financeiro] || "–", tone: r.controle_financeiro === "sim" ? "green" : r.controle_financeiro === "parcial" ? "amber" : "red" },
  ];
  const temBudget = r.budget_valor && r.budget_valor !== "nd";
  const budget = ((DG_MOEDA[r.budget_moeda] || "") + " " + (DG_BUD[r.budget_valor] || "–")).trim() + (temBudget ? " / mês" : "");
  function toUrl(raw) { return raw && !raw.startsWith("http") ? "https://" + raw : (raw || ""); }
  function igHandle(v) { return v.match(/instagram\.com\/([^/?#]+)/)?.[1] || v.replace(/^@/, ""); }
  function liHandle(v) { return v.match(/linkedin\.com\/(?:in|company)\/([^/?#]+)/)?.[1] || null; }
  function ytHandle(v) { return v.match(/youtube\.com\/(?:@|c\/|channel\/|user\/)?([^/?#]+)/)?.[1] || v.match(/youtu\.be\/([^/?#]+)/)?.[1] || null; }
  function fbHandle(v) { return v.match(/facebook\.com\/([^/?#]+)/)?.[1] || null; }
  function xHandle(v)  { return v.match(/(?:twitter|x)\.com\/([^/?#]+)/)?.[1] || v.replace(/^@/, ""); }
  function ttHandle(v) { return v.match(/tiktok\.com\/@?([^/?#]+)/)?.[1] || v.replace(/^@/, ""); }
  const presenca = [];
  if (r.site)       presenca.push({ type: "site",      label: r.site.replace(/^https?:\/\//, "").replace(/\/$/, ""),        url: toUrl(r.site) });
  if (r.instagram)  presenca.push({ type: "instagram", label: "@" + igHandle(r.instagram),                                  url: r.instagram.startsWith("http") ? r.instagram : "https://instagram.com/" + igHandle(r.instagram) });
  if (r.linkedin)   presenca.push({ type: "linkedin",  label: liHandle(r.linkedin) || "LinkedIn",                           url: toUrl(r.linkedin) });
  if (r.youtube)    presenca.push({ type: "youtube",   label: (ytHandle(r.youtube) ? "@" + ytHandle(r.youtube) : "YouTube"), url: toUrl(r.youtube) });
  if (r.facebook)   presenca.push({ type: "facebook",  label: fbHandle(r.facebook) || "Facebook",                           url: toUrl(r.facebook) });
  if (r.x_twitter)  presenca.push({ type: "x_twitter", label: "@" + xHandle(r.x_twitter),                                   url: r.x_twitter.startsWith("http") ? r.x_twitter : "https://x.com/" + xHandle(r.x_twitter) });
  if (r.tiktok)     presenca.push({ type: "tiktok",    label: "@" + ttHandle(r.tiktok),                                     url: r.tiktok.startsWith("http") ? r.tiktok : "https://tiktok.com/@" + ttHandle(r.tiktok) });
  if (r.outras_redes) presenca.push({ type: "other",   label: r.outras_redes.replace(/^https?:\/\//, "").replace(/\/$/, ""), url: r.outras_redes.startsWith("http") ? r.outras_redes : "" });
  const facts = [
    { k: "Negócio",     v: r.empresa         || "–" },
    { k: "Função",      v: r.cargo           || "–" },
    { k: "Setor",       v: r.setor           || "–" },
    { k: "Porte",       v: r.tamanho_empresa || "–" },
    { k: "Localização", v: r.cidade_pais     || "–" },
  ];
  const firstName = (r.nome || "").trim().split(/\s+/)[0] || "";
  return {
    raw: r, nome: r.nome || "Cliente", firstName, empresa: r.empresa || "",
    facts, presenca, onde, ferramentas, status, budget,
    mat, matLabel: DG_MAT[mat] || "–",
    objetivo: r.objetivo_mentoria || "", prioridade: r.prioridade || "", jaTentou: r.ja_tentou || "",
    diag: r.diagnostico || null,
  };
}

function DgSecHead({ n, eyebrow, title }) {
  return (
    <div style={{ marginBottom: 18 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 9 }}>
        <span style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 14, color: "var(--accent)" }}>{n}</span>
        <span style={{ fontSize: 12, fontWeight: 800, letterSpacing: ".05em", textTransform: "uppercase", color: "var(--primary)", whiteSpace: "nowrap" }}>{eyebrow}</span>
      </div>
      <h2 style={{ fontFamily: "var(--font-display)", fontSize: 21, fontWeight: 800, lineHeight: 1.2, color: "var(--ink)", margin: 0 }}>{title}</h2>
    </div>
  );
}

function DgPills({ items, accent }) {
  return (
    <div style={{ display: "flex", flexWrap: "wrap", gap: 9 }}>
      {items.length === 0 && <span style={{ fontSize: 13.5, color: "var(--muted)" }}>–</span>}
      {items.map((p, i) => (
        <span key={i} style={{ display: "inline-flex", padding: "8px 14px", borderRadius: 999, background: accent ? "var(--primary-soft)" : "var(--surface-2)", border: "1px solid var(--line)", fontSize: 13.5, fontWeight: 600, color: accent ? "var(--primary)" : "var(--ink)" }}>{p}</span>
      ))}
    </div>
  );
}

function DgState({ icon, title, sub, children }) {
  useLucide();
  return (
    <div className="panel panel-lg" style={{ textAlign: "center", padding: "48px 32px" }}>
      <span style={{ width: 60, height: 60, borderRadius: 16, background: "var(--primary-soft)", color: "var(--primary)", display: "grid", placeItems: "center", margin: "0 auto 18px" }}>
        <Icon name={icon} style={{ fontSize: 26 }} />
      </span>
      <h3 style={{ fontSize: 18, fontWeight: 800 }}>{title}</h3>
      {sub && <p style={{ color: "var(--muted)", fontSize: 14, maxWidth: "46ch", margin: "8px auto 0", lineHeight: 1.6 }}>{sub}</p>}
      {children && <div style={{ marginTop: 18 }}>{children}</div>}
    </div>
  );
}

function DiagnosticReport({ d, onPrint }) {
  return (
    <React.Fragment>
      <div className="panel panel-lg">
        <div style={{ display: "flex", justifyContent: "space-between", gap: 18, flexWrap: "wrap", alignItems: "flex-start" }}>
          <div style={{ display: "flex", gap: 15, minWidth: 0 }}>
            <span style={{ width: 52, height: 52, borderRadius: 15, background: "var(--primary-soft)", color: "var(--primary)", display: "grid", placeItems: "center", flexShrink: 0 }}>
              <Icon name="stethoscope" style={{ fontSize: 24 }} />
            </span>
            <div style={{ minWidth: 0 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
                <h2 style={{ fontSize: 23, fontWeight: 800, lineHeight: 1.2 }}>Diagnóstico</h2>
                <Badge kind={d.diag ? "green" : "amber"}>{d.diag ? "Concluído" : "Leitura do onboarding"}</Badge>
              </div>
              <div style={{ fontSize: 14, color: "var(--muted)", marginTop: 3 }}>Sessão 00 · {d.empresa || d.nome}</div>
            </div>
          </div>
          <button className="btn btn-primary" onClick={onPrint}><Icon name="file-down" style={{ fontSize: 16 }} /> Baixar PDF</button>
        </div>
        <hr className="hairline" style={{ margin: "18px 0" }} />
        <p style={{ fontSize: 14.5, color: "var(--ink)", lineHeight: 1.6, maxWidth: "72ch", margin: 0 }}>
          Olá, {d.firstName || d.nome}. Esta é a leitura do seu onboarding — o ponto de partida da sua jornada COSI. Tudo aqui vem das suas próprias respostas.
        </p>
      </div>

      <div className="panel panel-lg">
        <DgSecHead n="01" eyebrow="Perfil & contexto" title={"Quem é a " + (d.firstName || "cliente")} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 14 }}>
          {d.facts.map((f, i) => (
            <div key={i} style={{ gridColumn: i === 4 ? "1 / -1" : undefined, background: "var(--surface-2)", border: "1px solid var(--line)", borderRadius: 14, padding: "18px 22px" }}>
              <div style={{ fontSize: 11.5, fontWeight: 800, letterSpacing: ".05em", textTransform: "uppercase", color: "var(--muted)" }}>{f.k}</div>
              <div style={{ fontSize: 16, fontWeight: 700, color: "var(--ink)", marginTop: 6, lineHeight: 1.4, wordBreak: "break-word" }}>{f.v}</div>
            </div>
          ))}
        </div>
        {d.presenca && d.presenca.length > 0 && (
          <div style={{ marginTop: 16 }}>
            <div style={{ fontSize: 11.5, fontWeight: 800, letterSpacing: ".05em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 10 }}>Presença online</div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 9 }}>
              {d.presenca.map((p, i) => {
                const BRAND = {
                  site:      { icon: "globe",      color: "#4337A5", bg: "rgba(67,55,165,.10)" },
                  instagram: { icon: "instagram",  color: "#F77737", bg: "rgba(247,119,55,.10)" },
                  linkedin:  { icon: "linkedin",   color: "#0A66C2", bg: "rgba(10,102,194,.10)" },
                  youtube:   { icon: "youtube",    color: "#FF0000", bg: "rgba(255,0,0,.10)" },
                  facebook:  { icon: "facebook",   color: "#1877F2", bg: "rgba(24,119,242,.10)" },
                  x_twitter: { icon: "twitter",    color: "#000000", bg: "rgba(0,0,0,.07)" },
                  tiktok:    { icon: null,          color: "#010101", bg: "rgba(0,0,0,.07)" },
                  other:     { icon: "link",        color: "#5F6175", bg: "var(--surface-2)" },
                };
                const b = BRAND[p.type] || BRAND.other;
                const chipStyle = { display: "inline-flex", alignItems: "center", gap: 7, padding: "8px 16px", borderRadius: 999, background: b.bg, border: "1px solid " + b.color + "33", fontSize: 13.5, fontWeight: 700, color: b.color, textDecoration: "none", transition: "opacity .15s" };
                const TikTokSvg = () => (
                  <svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor" style={{ flexShrink: 0 }}>
                    <path d="M19.59 6.69a4.83 4.83 0 0 1-3.77-4.25V2h-3.45v13.67a2.89 2.89 0 0 1-2.88 2.5 2.89 2.89 0 0 1-2.89-2.89 2.89 2.89 0 0 1 2.89-2.89c.28 0 .54.04.79.1V9.01a6.34 6.34 0 0 0-.79-.05 6.34 6.34 0 0 0-6.34 6.34 6.34 6.34 0 0 0 6.34 6.34 6.34 6.34 0 0 0 6.33-6.34V8.69a8.18 8.18 0 0 0 4.77 1.5V6.74a4.85 4.85 0 0 1-1-.05z"/>
                  </svg>
                );
                const iconEl = p.type === "tiktok" ? <TikTokSvg /> : b.icon ? <Icon name={b.icon} style={{ fontSize: 15 }} /> : null;
                const inner = <React.Fragment>{iconEl}{p.label}</React.Fragment>;
                return p.url
                  ? <a key={i} href={p.url} target="_blank" rel="noopener noreferrer" style={chipStyle}>{inner}</a>
                  : <span key={i} style={chipStyle}>{inner}</span>;
              })}
            </div>
          </div>
        )}
      </div>

      <div className="panel panel-lg">
        <DgSecHead n="02" eyebrow="Diagnóstico rápido" title="Onde vivem os dados hoje" />
        <div style={{ display: "grid", gap: 22 }}>
          <div>
            <div style={{ fontSize: 11.5, fontWeight: 800, letterSpacing: ".05em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 10 }}>Fontes de dados</div>
            <DgPills items={d.onde} />
          </div>
          <div>
            <div style={{ fontSize: 11.5, fontWeight: 800, letterSpacing: ".05em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 10 }}>Ferramentas do dia a dia</div>
            <DgPills items={d.ferramentas} accent />
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(200px,1fr))", gap: 12 }}>
            {d.status.map((s, i) => (
              <div key={i} style={{ background: "var(--surface-2)", border: "1px solid var(--line)", borderRadius: 14, padding: "14px 16px", display: "flex", alignItems: "center", gap: 12 }}>
                <span style={{ width: 14, height: 14, borderRadius: "50%", background: DG_TONE[s.tone], flexShrink: 0 }}></span>
                <div>
                  <div style={{ fontSize: 12, color: "var(--muted)", fontWeight: 600 }}>{s.label}</div>
                  <div style={{ fontSize: 15, fontWeight: 700, color: "var(--ink)" }}>{s.value}</div>
                </div>
              </div>
            ))}
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 12, background: "var(--surface-2)", border: "1px solid var(--line)", borderRadius: 14, padding: "14px 18px" }}>
            <Icon name="wallet" style={{ fontSize: 18, color: "var(--primary)" }} />
            <span style={{ fontSize: 13.5, fontWeight: 700, color: "var(--muted)", textTransform: "uppercase", letterSpacing: ".04em" }}>Budget p/ ferramentas</span>
            <span style={{ marginLeft: "auto", fontFamily: "var(--font-display)", fontSize: 18, fontWeight: 800, color: "var(--ink)" }}>{d.budget}</span>
          </div>
        </div>
      </div>

      <div className="panel panel-lg">
        <DgSecHead n="03" eyebrow="Diagnóstico rápido" title="Maturidade de dados" />
        <div style={{ display: "flex", gap: 28, alignItems: "center", flexWrap: "wrap" }}>
          <div style={{ textAlign: "center", flexShrink: 0 }}>
            <div style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 66, lineHeight: 1, color: "var(--primary)" }}>{d.mat}</div>
            <div style={{ fontSize: 13, color: "var(--muted)", fontWeight: 700 }}>de 5</div>
          </div>
          <div style={{ flex: 1, minWidth: 280 }}>
            <div style={{ display: "flex", gap: 8 }}>
              {[1,2,3,4,5].map(n => (
                <div key={n} style={{ flex: 1, height: 48, borderRadius: 12, display: "grid", placeItems: "center", fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 18, border: "1px solid var(--line)", background: n < d.mat ? "#7B71D9" : n === d.mat ? "var(--accent)" : "var(--surface-2)", color: n <= d.mat ? "#fff" : "var(--muted)" }}>{n}</div>
              ))}
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5, color: "var(--muted)", fontWeight: 600, marginTop: 8 }}>
              <span>Tudo no feeling</span><span>Decisões 100% em dados</span>
            </div>
            <p style={{ fontSize: 14, color: "var(--ink)", lineHeight: 1.55, margin: "12px 0 0" }}>
              <strong style={{ color: "var(--primary)" }}>{d.matLabel}.</strong> É o ponto de partida — e exatamente onde o método COSI mais acelera.
            </p>
          </div>
        </div>
      </div>

      <div className="panel panel-lg">
        <DgSecHead n="04" eyebrow="Objetivo da mentoria" title="O que você quer resolver" />
        {d.objetivo && (
          <div style={{ background: "#FCEFE7", borderLeft: "5px solid var(--accent)", borderRadius: "0 16px 16px 0", padding: "22px 26px", marginBottom: 16 }}>
            <p style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 21, lineHeight: 1.4, color: "var(--ink)", margin: 0 }}>"{d.objetivo}"</p>
          </div>
        )}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1.4fr", gap: 14 }}>
          <div style={{ background: "var(--primary)", borderRadius: 14, padding: "16px 18px", color: "#fff" }}>
            <div style={{ fontSize: 11.5, fontWeight: 800, letterSpacing: ".05em", textTransform: "uppercase", color: "var(--lav)" }}>Prioridade nº 1</div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 17, fontWeight: 800, marginTop: 6, lineHeight: 1.25 }}>{d.prioridade || "–"}</div>
          </div>
          {d.jaTentou && (
            <div style={{ background: "var(--surface-2)", border: "1px solid var(--line)", borderRadius: 14, padding: "16px 18px" }}>
              <div style={{ fontSize: 11.5, fontWeight: 800, letterSpacing: ".05em", textTransform: "uppercase", color: "var(--muted)" }}>Já tentou, sem sucesso</div>
              <p style={{ fontSize: 14, color: "var(--ink)", lineHeight: 1.55, margin: "6px 0 0" }}>{d.jaTentou}</p>
            </div>
          )}
        </div>
      </div>

      {d.diag && d.diag.resumo ? (
        <div className="panel panel-lg">
          <DgSecHead n="05" eyebrow="Leitura da Cosidata" title="A síntese do diagnóstico" />
          <div style={{ borderRadius: 18, padding: 24, background: "linear-gradient(135deg,var(--primary),#5F53CA 60%,var(--accent))", color: "#fff" }}>
            <div style={{ fontSize: 12, fontWeight: 800, textTransform: "uppercase", letterSpacing: ".06em", opacity: .85 }}>Síntese</div>
            <div style={{ fontSize: 18, fontWeight: 700, marginTop: 8, lineHeight: 1.5 }}>{d.diag.resumo}</div>
          </div>
          {d.diag.focos && d.diag.focos.length > 0 && (
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(220px,1fr))", gap: 12, marginTop: 16 }}>
              {d.diag.focos.map((f, i) => (
                <div key={i} style={{ border: "1px solid var(--line)", borderRadius: 14, padding: 16, background: "var(--surface-2)" }}>
                  <div style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 18, color: "var(--accent)" }}>{f.n}</div>
                  <div style={{ fontWeight: 700, fontSize: 15, margin: "6px 0" }}>{f.titulo}</div>
                  <p style={{ margin: 0, fontSize: 13.5, color: "var(--muted)", lineHeight: 1.55 }}>{f.texto}</p>
                </div>
              ))}
            </div>
          )}
          {d.diag.metodo && d.diag.metodo.length > 0 && (
            <div style={{ marginTop: 22 }}>
              <div style={{ fontSize: 12, fontWeight: 800, letterSpacing: ".05em", textTransform: "uppercase", color: "var(--primary)", marginBottom: 4 }}>O método COSI</div>
              <p style={{ fontSize: 13.5, color: "var(--muted)", margin: "0 0 14px", lineHeight: 1.5 }}>Quatro fases, da base à inteligência — nessa ordem.</p>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(210px,1fr))", gap: 12 }}>
                {d.diag.metodo.map((m, i) => {
                  const atual = i === (d.diag.faseAtual ?? -1);
                  const feita = i < (d.diag.faseAtual ?? -1);
                  return (
                    <div key={i} style={{ border: "1px solid " + (atual ? "var(--accent)" : "var(--line)"), borderRadius: 16, padding: "18px 16px", background: atual ? "var(--accent-soft)" : "var(--surface-2)", display: "flex", flexDirection: "column", gap: 10 }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                        <span style={{ width: 38, height: 38, borderRadius: 11, flexShrink: 0, display: "grid", placeItems: "center", fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 19, color: "#fff", background: atual ? "var(--accent)" : feita ? "var(--green)" : "var(--primary)" }}>{m.letra}</span>
                        <div style={{ minWidth: 0, flex: 1 }}>
                          <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
                            <span style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 16, color: "var(--ink)" }}>{m.fase}</span>
                            {atual && <span style={{ fontSize: 9.5, fontWeight: 800, textTransform: "uppercase", color: "#fff", background: "var(--accent)", borderRadius: 999, padding: "3px 8px" }}>Você está aqui</span>}
                            {feita && <Icon name="check-circle-2" style={{ fontSize: 16, color: "var(--green)" }} />}
                          </div>
                          <div style={{ fontSize: 11.5, fontWeight: 700, color: atual ? "var(--accent-d)" : "var(--muted)", marginTop: 2 }}>{m.sessoes}</div>
                        </div>
                      </div>
                      <p style={{ margin: 0, fontSize: 13, color: "var(--muted)", lineHeight: 1.5 }}>{m.t}</p>
                    </div>
                  );
                })}
              </div>
            </div>
          )}
          {d.diag.proximos && (
            <div style={{ marginTop: 16, display: "flex", alignItems: "center", gap: 12, background: "var(--primary-soft)", borderRadius: 14, padding: "14px 18px" }}>
              <Icon name="flag" style={{ fontSize: 18, color: "var(--primary)" }} />
              <div><span style={{ fontWeight: 800, color: "var(--primary)" }}>Próximo passo · </span><span style={{ fontSize: 14, color: "var(--ink)" }}>{d.diag.proximos}</span></div>
            </div>
          )}
        </div>
      ) : (
        <div className="panel panel-lg" style={{ display: "flex", alignItems: "center", gap: 14 }}>
          <span style={{ width: 46, height: 46, borderRadius: 13, background: "var(--accent-soft)", color: "var(--accent-d)", display: "grid", placeItems: "center", flexShrink: 0 }}>
            <Icon name="sparkles" style={{ fontSize: 21 }} />
          </span>
          <div>
            <div style={{ fontWeight: 700, fontSize: 15 }}>A leitura da Cosidata aparecerá aqui</div>
            <div style={{ fontSize: 13.5, color: "var(--muted)", marginTop: 3, lineHeight: 1.55 }}>Depois da sua sessão de diagnóstico, a síntese fica disponível nesta página.</div>
          </div>
        </div>
      )}
    </React.Fragment>
  );
}

function ClientDiagnostic({ user, row: providedRow, diagFallback, onPrint }) {
  useLucide();
  const [st, setSt] = useStateDg(providedRow ? { s: "ok", row: providedRow } : { s: "loading" });

  useEffectDg(() => {
    if (providedRow) { setSt({ s: "ok", row: providedRow }); return; }
    let alive = true;
    (async () => {
      try {
        const email = user && (user.email || user.mail);
        const token = user && (user.token || user.access_token);
        if (!email) { setSt({ s: "error", msg: "Não foi possível identificar o e-mail da sessão." }); return; }
        const row = await fetchOnboardingRow(email, token);
        if (!alive) return;
        setSt(row ? { s: "ok", row } : { s: "empty" });
      } catch (e) {
        if (alive) setSt({ s: "error", msg: e.message });
      }
    })();
    return () => { alive = false; };
  }, [user, providedRow]);

  useEffectDg(() => { if (window.lucide) window.lucide.createIcons(); });

  const doPrint = onPrint || (() => window.print());
  if (st.s === "loading") return <DgState icon="loader" title="Carregando seu diagnóstico…" sub="Buscando as suas respostas do onboarding." />;
  if (st.s === "error")   return <DgState icon="triangle-alert" title="Não consegui carregar o diagnóstico" sub={st.msg} />;
  if (st.s === "empty" && !diagFallback) return <DgState icon="clipboard-list" title="Onboarding ainda não preenchido" sub="Assim que você completar o formulário de onboarding, o diagnóstico aparece aqui automaticamente." />;

  const row = Object.assign({}, st.s === "empty" ? {} : st.row);
  if (!row.diagnostico && diagFallback) row.diagnostico = diagFallback;
  const d = normalizeOnboarding(row);
  return <DiagnosticReport d={d} onPrint={doPrint} />;
}

Object.assign(window, { ClientDiagnostic, normalizeOnboarding, DiagnosticReport, fetchOnboardingRow });
