// screen-discovery.jsx — Tela de Discovery comercial (USO INTERNO DashM)
// Permite anotar respostas das 26 perguntas do PLAN-capivaras-discovery na reunião.
// Persiste em localStorage. Exporta JSON pra colar no DOSSIE do cliente.

const DISCOVERY_VERSION = 1;
const DISCOVERY_STORAGE_KEY = "cores-pdv-discovery-v1";

const DISCOVERY_BLOCKS = [
  {
    id: "bloco-1",
    title: "Bloco 1 — Quebra-gelo e fôlego financeiro",
    duration: "5-10 min",
    color: "#06b6d4",
    questions: [
      { id: "p1", q: "Como surgiu a ideia de abrir a Capivara's? É hobby virando negócio ou já tinha família no ramo?" },
      { id: "p2", q: "Vai tocar a loja sozinho ou tem sócio/funcionário? Quantas pessoas vão mexer no caixa?" },
      { id: "p3", q: "Quando abre a loja oficialmente? Já tem ponto fechado, alvará, fornecedor?" },
      { id: "p4", q: "Investimento inicial total separado (estoque + ponto + sistema + tudo)?", hint: "Se < R$ 50k, sistema não pode comer mais que R$ 3-5k de setup" },
    ],
  },
  {
    id: "bloco-2",
    title: "Bloco 2 — Operação do dia a dia",
    duration: "10-15 min",
    color: "#3b82f6",
    questions: [
      { id: "p5", q: "Estimativa de vendas/dia nos primeiros 3 meses? E daqui a 1 ano?" },
      { id: "p6", q: "Quantos SKUs vai cadastrar pra começar?", hint: "Define se cabe no Essencial (até 1.000)" },
      { id: "p7", q: "Quantos caixas/PDVs funcionando ao mesmo tempo?" },
      { id: "p8", q: "Hardware do balcão — computador, maquininha (modelo?), impressora térmica (modelo?), leitor código barras, balança?" },
      { id: "p9", q: "Vende mais ticket pequeno (anzol R$ 20-50) ou alto (vara R$ 500, motor R$ 15k)? Ticket médio esperado?" },
      { id: "p10", q: "Vai ter fiado/crediário?", hint: "Se sim → add-on +R$ 59/mês ou Profissional" },
      { id: "p11", q: "Vai ter vendedor com comissão? Quantas pessoas? Que %?" },
      { id: "p12", q: "Pretende vender online também? (primeira reação antes do Bloco 4)" },
    ],
  },
  {
    id: "bloco-3",
    title: "Bloco 3 — Fiscal e legal",
    duration: "5-10 min",
    color: "#f59e0b",
    questions: [
      { id: "p13", q: "Já tem contador? Ele já abriu a empresa?" },
      { id: "p14", q: "Regime tributário escolhido? MEI / Simples / não sabe?", hint: "MEI tem limite R$ 81k/ano — pra loja de pesca estoura rápido" },
      { id: "p15", q: "Já tem certificado digital A1 (arquivo .pfx)?", hint: "Custa R$ 200-400/ano. Se não tem, +R$ 300 no setup" },
      { id: "p16", q: "Vai emitir NF-e B2B (vender pra outra empresa)?", hint: "Se sim, plano precisa ser Profissional" },
    ],
  },
  {
    id: "bloco-4",
    title: "Bloco 4 — Marketplace (deixar ELE decidir)",
    duration: "10-15 min",
    color: "#10b981",
    questions: [
      { id: "p17", q: "Já tem conta vendedor em algum marketplace? Ou do zero?", hint: "Abrir conta leva 1-2 semanas" },
      { id: "p18", q: "% do faturamento esperado: loja física vs marketplace vs e-commerce próprio?" },
      { id: "p19", q: "Prefere vender no marketplace (paga taxa, ganha tráfego) ou ter e-commerce próprio (sem taxa, mas tem que trazer tráfego)?", hint: "RESPOSTA-CHAVE — define escopo" },
      { id: "p20", q: "Se fosse começar com UM marketplace só, qual seria? ML / Shopee / Amazon?" },
    ],
  },
  {
    id: "bloco-5",
    title: "Bloco 5 — Internet, contingência e PWA",
    duration: "3-5 min",
    color: "#8b5cf6",
    questions: [
      { id: "p21", q: "Internet da loja — provedor? fibra ou rádio? cai com frequência?" },
      { id: "p22", q: "Tem 4G de backup (chip no roteador) ou nobreak?" },
    ],
  },
  {
    id: "bloco-6",
    title: "Bloco 6 — Concorrência e expectativa de preço",
    duration: "5-10 min",
    color: "#ec4899",
    questions: [
      { id: "p23", q: "Quanto deu Bling + Loja Integrada somados? Qual plano cada um?" },
      { id: "p24", q: "Eles cobraram setup/implantação? Quanto?" },
      { id: "p25", q: "O que te incomodou na cotação deles?", hint: "Tudo que ele reclamar é diferencial seu" },
      { id: "p26", q: "Investimento mensal aceitável num sistema pros primeiros 6 meses?", hint: "RESPOSTA-CHAVE — se < R$ 250 puxar com argumento" },
    ],
  },
  {
    id: "decisoes",
    title: "Decisões pós-reunião",
    duration: "preencher na hora",
    color: "#ef4444",
    questions: [
      { id: "d1", q: "Plano escolhido (Enxuto R$ 299 / Profissional+ML R$ 399 / Completo R$ 599)" },
      { id: "d2", q: "Marketplaces no escopo (nenhum / ML / ML+Shopee / +Amazon)" },
      { id: "d3", q: "E-commerce próprio? (sim / não / depois)" },
      { id: "d4", q: "Crediário no MVP? (sim / não)" },
      { id: "d5", q: "Comissão de vendedor? (sim / não)" },
      { id: "d6", q: "Tem certificado A1? (sim / não → +R$ 300 setup)" },
      { id: "d7", q: "Tem contador? (sim / não → indica parceiro)" },
      { id: "d8", q: "Hardware impressora — modelo" },
      { id: "d9", q: "Hardware maquininha — modelo + TEF integrado?" },
      { id: "d10", q: "Data de abertura da loja" },
      { id: "d11", q: "Fechou agora ou pensar?" },
      { id: "d12", q: "Próximo passo combinado (follow-up sexta? assinou?)" },
    ],
  },
];

function loadAnswers() {
  try {
    const raw = localStorage.getItem(DISCOVERY_STORAGE_KEY);
    if (!raw) return { client: "", date: new Date().toISOString().slice(0, 10), answers: {} };
    const parsed = JSON.parse(raw);
    return {
      client: parsed.client || "",
      date: parsed.date || new Date().toISOString().slice(0, 10),
      answers: parsed.answers || {},
    };
  } catch {
    return { client: "", date: new Date().toISOString().slice(0, 10), answers: {} };
  }
}

function saveAnswers(state) {
  try {
    localStorage.setItem(
      DISCOVERY_STORAGE_KEY,
      JSON.stringify({ ...state, version: DISCOVERY_VERSION, updated_at: new Date().toISOString() })
    );
  } catch (e) {
    console.warn("Não consegui salvar no localStorage:", e);
  }
}

function downloadJSON(state) {
  const payload = {
    version: DISCOVERY_VERSION,
    exported_at: new Date().toISOString(),
    client: state.client || "Cliente sem nome",
    meeting_date: state.date,
    blocks: DISCOVERY_BLOCKS.map((b) => ({
      block_id: b.id,
      block_title: b.title,
      questions: b.questions.map((q) => ({
        id: q.id,
        question: q.q,
        answer: (state.answers[q.id] || "").trim(),
      })),
    })),
  };
  const blob = new Blob([JSON.stringify(payload, null, 2)], { type: "application/json" });
  const url = URL.createObjectURL(blob);
  const safeClient = (state.client || "cliente").toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-|-$/g, "");
  const a = document.createElement("a");
  a.href = url;
  a.download = `discovery-${safeClient}-${state.date}.json`;
  document.body.appendChild(a);
  a.click();
  setTimeout(() => {
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  }, 0);
}

function downloadMarkdown(state) {
  const lines = [];
  lines.push(`# Discovery — ${state.client || "Cliente sem nome"}`);
  lines.push(`> Data da reunião: ${state.date}`);
  lines.push(`> Exportado em: ${new Date().toISOString()}`);
  lines.push("");
  DISCOVERY_BLOCKS.forEach((b) => {
    lines.push(`## ${b.title}`);
    lines.push("");
    b.questions.forEach((q) => {
      const a = (state.answers[q.id] || "").trim();
      lines.push(`### ${q.id.toUpperCase()}. ${q.q}`);
      lines.push("");
      lines.push(a ? a : "_(sem resposta)_");
      lines.push("");
    });
  });
  const md = lines.join("\n");
  const blob = new Blob([md], { type: "text/markdown" });
  const url = URL.createObjectURL(blob);
  const safeClient = (state.client || "cliente").toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-|-$/g, "");
  const a = document.createElement("a");
  a.href = url;
  a.download = `discovery-${safeClient}-${state.date}.md`;
  document.body.appendChild(a);
  a.click();
  setTimeout(() => {
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  }, 0);
}

function DiscoveryScreen({ onToast }) {
  const [state, setState] = React.useState(() => loadAnswers());
  const [activeBlock, setActiveBlock] = React.useState("bloco-1");

  React.useEffect(() => {
    saveAnswers(state);
  }, [state]);

  function updateAnswer(qid, val) {
    setState((s) => ({ ...s, answers: { ...s.answers, [qid]: val } }));
  }

  function clearAll() {
    if (!confirm("Apagar TODAS as respostas deste discovery? (não dá pra desfazer)")) return;
    const fresh = { client: "", date: new Date().toISOString().slice(0, 10), answers: {} };
    setState(fresh);
    saveAnswers(fresh);
    onToast?.({ msg: "Discovery resetado", kind: "ok" });
  }

  const totalQuestions = DISCOVERY_BLOCKS.reduce((acc, b) => acc + b.questions.length, 0);
  const answered = Object.values(state.answers).filter((v) => (v || "").trim().length > 0).length;
  const progress = totalQuestions ? Math.round((answered / totalQuestions) * 100) : 0;

  return (
    <div style={{ maxWidth: 1100, margin: "0 auto" }}>
      {/* Header */}
      <div style={{
        background: "linear-gradient(135deg, #1e3a8a 0%, #3b82f6 100%)",
        color: "white", padding: "1.5rem 1.75rem", borderRadius: 14, marginBottom: 16,
      }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 16, flexWrap: "wrap" }}>
          <div>
            <h2 style={{ margin: 0, fontSize: "1.4rem" }}>🎯 Discovery comercial</h2>
            <p style={{ margin: "4px 0 0", opacity: 0.9, fontSize: ".9rem" }}>
              26 perguntas pra entender as dores do cliente antes de fechar preço. Respostas salvas automaticamente no navegador.
            </p>
          </div>
          <div style={{ textAlign: "right", minWidth: 180 }}>
            <div style={{ fontSize: ".8rem", opacity: 0.85 }}>Progresso</div>
            <div style={{ fontSize: "1.6rem", fontWeight: 800, lineHeight: 1 }}>{progress}%</div>
            <div style={{ fontSize: ".8rem", opacity: 0.85 }}>{answered} / {totalQuestions} respondidas</div>
          </div>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 200px", gap: 12, marginTop: 16 }}>
          <label style={{ display: "flex", flexDirection: "column", gap: 4 }}>
            <span style={{ fontSize: ".78rem", opacity: 0.85 }}>Nome do cliente</span>
            <input
              type="text"
              value={state.client}
              onChange={(e) => setState((s) => ({ ...s, client: e.target.value }))}
              placeholder="Ex: Capivara's Fishing"
              style={{
                padding: "8px 12px", borderRadius: 8, border: "1px solid rgba(255,255,255,.25)",
                background: "rgba(255,255,255,.12)", color: "white", fontSize: ".95rem",
              }}
            />
          </label>
          <label style={{ display: "flex", flexDirection: "column", gap: 4 }}>
            <span style={{ fontSize: ".78rem", opacity: 0.85 }}>Data da reunião</span>
            <input
              type="date"
              value={state.date}
              onChange={(e) => setState((s) => ({ ...s, date: e.target.value }))}
              style={{
                padding: "8px 12px", borderRadius: 8, border: "1px solid rgba(255,255,255,.25)",
                background: "rgba(255,255,255,.12)", color: "white", fontSize: ".95rem",
              }}
            />
          </label>
        </div>
      </div>

      {/* Action bar */}
      <div style={{
        display: "flex", gap: 8, marginBottom: 16, flexWrap: "wrap",
        background: "var(--card)", padding: "12px 16px", borderRadius: 12, border: "1px solid var(--line)",
      }}>
        <button onClick={() => downloadJSON(state)} className="btn btn-primary" style={{ fontSize: ".85rem" }}>
          📥 Baixar JSON
        </button>
        <button onClick={() => downloadMarkdown(state)} className="btn" style={{ fontSize: ".85rem" }}>
          📝 Baixar Markdown
        </button>
        <button onClick={clearAll} className="btn btn-danger" style={{ marginLeft: "auto", fontSize: ".85rem" }}>
          🗑️ Resetar tudo
        </button>
      </div>

      {/* Block tabs */}
      <div style={{ display: "flex", gap: 6, marginBottom: 16, flexWrap: "wrap" }}>
        {DISCOVERY_BLOCKS.map((b) => {
          const blockAnswered = b.questions.filter((q) => (state.answers[q.id] || "").trim().length > 0).length;
          const isActive = activeBlock === b.id;
          return (
            <button
              key={b.id}
              onClick={() => setActiveBlock(b.id)}
              style={{
                padding: "8px 14px", borderRadius: 8, border: "1px solid var(--line)",
                background: isActive ? b.color : "var(--card)",
                color: isActive ? "white" : "var(--text)",
                fontSize: ".82rem", fontWeight: 600, cursor: "pointer",
                display: "inline-flex", alignItems: "center", gap: 6,
              }}
            >
              <span>{b.title.replace(/^Bloco \d+ — /, "").replace(/^Decisões /, "Decisões")}</span>
              <span style={{
                background: isActive ? "rgba(255,255,255,.25)" : "var(--bg)",
                padding: "2px 7px", borderRadius: 999, fontSize: ".72rem", fontWeight: 700,
              }}>
                {blockAnswered}/{b.questions.length}
              </span>
            </button>
          );
        })}
      </div>

      {/* Active block */}
      {DISCOVERY_BLOCKS.filter((b) => b.id === activeBlock).map((b) => (
        <div key={b.id} style={{
          background: "var(--card)", borderRadius: 12, padding: "1.25rem 1.5rem",
          border: "1px solid var(--line)", borderLeft: `5px solid ${b.color}`,
        }}>
          <div style={{ marginBottom: 16 }}>
            <h3 style={{ margin: 0, color: b.color, fontSize: "1.1rem" }}>{b.title}</h3>
            <p style={{ margin: "4px 0 0", color: "var(--muted)", fontSize: ".8rem" }}>⏱ {b.duration}</p>
          </div>

          {b.questions.map((q) => (
            <div key={q.id} style={{ marginBottom: 18 }}>
              <label style={{ display: "block", fontWeight: 600, marginBottom: 4, fontSize: ".95rem" }}>
                <span style={{
                  display: "inline-block", minWidth: 32, padding: "2px 6px", borderRadius: 6,
                  background: b.color, color: "white", fontSize: ".75rem", fontWeight: 700,
                  marginRight: 8, textAlign: "center",
                }}>
                  {q.id.toUpperCase()}
                </span>
                {q.q}
              </label>
              {q.hint && (
                <div style={{ fontSize: ".78rem", color: "var(--muted)", marginBottom: 6, marginLeft: 4 }}>
                  💡 {q.hint}
                </div>
              )}
              <textarea
                value={state.answers[q.id] || ""}
                onChange={(e) => updateAnswer(q.id, e.target.value)}
                placeholder="Anote a resposta aqui…"
                rows={3}
                style={{
                  width: "100%", padding: "10px 12px", borderRadius: 8,
                  border: "1px solid var(--line)", background: "var(--bg)", color: "var(--text)",
                  fontSize: ".92rem", resize: "vertical", fontFamily: "inherit", lineHeight: 1.5,
                }}
              />
            </div>
          ))}
        </div>
      ))}

      <p style={{ textAlign: "center", marginTop: 24, color: "var(--muted)", fontSize: ".8rem" }}>
        🔒 Respostas ficam apenas neste navegador (localStorage). Nada é enviado pra servidor.
      </p>
    </div>
  );
}

window.DiscoveryScreen = DiscoveryScreen;
