/* global React, SEQ_UI, SEQ_DATA */
const { Wordmark, Avatar, Icon, brl } = window.SEQ_UI;

const TEMPLATES = [
  {
    id: "kaleidos",
    name: "Kaleidos Editorial",
    sub: "Brutalist · papel + tinta + splash",
    tags: ["Editorial", "Bold", "Agência"],
    accent: "var(--kp-green)",
  },
  {
    id: "minimal",
    name: "Minimal Mono",
    sub: "Limpa, tipografia preta · pra freelancer técnico",
    tags: ["Minimal", "Técnico", "B2B"],
    accent: "var(--kp-cold)",
  },
  {
    id: "soft",
    name: "Soft Studio",
    sub: "Pastéis, tipografia macia · pra estúdios criativos",
    tags: ["Soft", "Criativo", "Estúdio"],
    accent: "var(--kp-pink-soft)",
  },
];

function Editor() {
  const [tpl, setTpl] = React.useState("kaleidos");
  const [tab, setTab] = React.useState("estrutura");
  const [files, setFiles] = React.useState([
    { name: "briefing-cliente.pdf", size: "1.2MB", views: 4, kind: "pdf" },
    { name: "moodboard-v2.png", size: "3.8MB", views: 7, kind: "img" },
    { name: "cronograma.xlsx", size: "44KB", views: 1, kind: "doc" },
  ]);
  const fileRef = React.useRef(null);

  const onUpload = (e) => {
    const list = Array.from(e.target.files || []);
    const adds = list.map(f => ({
      name: f.name,
      size: (f.size/1024/1024 < 1 ? Math.round(f.size/1024)+"KB" : (f.size/1024/1024).toFixed(1)+"MB"),
      views: 0,
      kind: f.name.match(/\.(jpg|jpeg|png|webp|gif)$/i) ? "img" : f.name.match(/\.pdf$/i) ? "pdf" : "doc",
    }));
    setFiles([...adds, ...files]);
  };

  return (
    <div style={{ minHeight: "100vh", background: "var(--kp-paper)" }}>
      <EditorTopBar />
      <div className="kp-container kp-container-wide" style={{ padding: "20px 28px 64px", maxWidth: 1400 }}>
        <PageTitle num="04" sub="Editor + Templates" title={<>Crie, escolha um <em>template</em><br/>e suba o que precisar.</>} />

        {/* Tabs */}
        <div style={{ display: "flex", gap: 0, marginBottom: 18 }}>
          {[["estrutura","Estrutura"],["templates","Templates"],["anexos","Anexos & PDFs"],["envio","Envio + tracking"]].map(([k,l]) => (
            <button key={k} onClick={()=>setTab(k)} style={{
              padding: "9px 16px",
              fontFamily: "var(--kp-mono)", fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase",
              border: "1.5px solid var(--kp-ink)", borderRight: "none",
              background: tab === k ? "var(--kp-ink)" : "var(--kp-white)",
              color: tab === k ? "var(--kp-paper)" : "var(--kp-ink)",
              cursor: "pointer",
            }}>{l}</button>
          ))}
          <div style={{ flex: 1, borderBottom: "1.5px solid var(--kp-ink)" }} />
        </div>

        {tab === "estrutura" && <Estrutura tpl={tpl} />}
        {tab === "templates" && <Templates tpl={tpl} setTpl={setTpl} />}
        {tab === "anexos" && <Anexos files={files} onUpload={onUpload} fileRef={fileRef} setFiles={setFiles} />}
        {tab === "envio" && <Envio />}
      </div>
    </div>
  );
}

function EditorTopBar() {
  return (
    <div style={{
      borderBottom: "1.5px solid var(--kp-ink)", background: "var(--kp-paper)",
      position: "sticky", top: 0, zIndex: 30,
    }}>
      <div className="kp-container kp-container-wide" style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "12px 28px", maxWidth: 1400 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
          <a href="#/propostas" className="kp-btn kp-btn-sm kp-btn-ghost"><Icon.back s={14}/> Propostas</a>
          <span style={{ color: "var(--kp-faint)" }}>|</span>
          <input className="kp-input" defaultValue="Nova proposta · sem título" style={{ width: 320, padding: "7px 10px", fontSize: 13 }} />
          <span className="status-chip status-chip--pending">Rascunho</span>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <button className="kp-btn kp-btn-sm">Salvar</button>
          <a href="#/publica" className="kp-btn kp-btn-sm">Pré-visualizar</a>
          <a href="#/proposta" className="kp-btn kp-btn-sm kp-btn-ink">Enviar →</a>
        </div>
      </div>
    </div>
  );
}

function PageTitle({ num, sub, title }) {
  return (
    <div style={{ marginBottom: 28 }}>
      <span className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.2em", color: "var(--kp-muted)" }}>
        Nº <em style={{ fontFamily: "var(--kp-display)", fontStyle: "italic", fontSize: 14, letterSpacing: 0 }}>{num}</em> · {sub}
      </span>
      <h1 className="kp-display" style={{ fontSize: "clamp(34px,4.4vw,52px)", lineHeight: 1, margin: "8px 0 0" }}>{title}</h1>
    </div>
  );
}

// ─── Estrutura (form blocks) ────────────────────────────
function Estrutura({ tpl }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1.1fr", gap: 20 }}>
      {/* Form */}
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        {[
          { l: "Título da proposta", v: "Módulo de Agendamento Inteligente com IA" },
          { l: "Cliente", v: "Diogo Costa · Costa & Filhos Imóveis" },
          { l: "Valor", v: "R$ 4.000,00", inputType: "money" },
          { l: "Pagamento", v: "50% entrada + 50% na entrega" },
        ].map((f) => (
          <label key={f.l} style={{ display: "block" }}>
            <span className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.18em", color: "var(--kp-muted)" }}>{f.l}</span>
            <input className="kp-input" defaultValue={f.v} style={{ marginTop: 6 }} />
          </label>
        ))}
        <Block n="01" t="Capa" body="Título · cliente · data" />
        <Block n="02" t="Sobre o projeto" body="Contexto e objetivos · 2 parágrafos" />
        <Block n="03" t="Escopo" body="Lista de entregáveis · 6 itens" />
        <Block n="04" t="Cronograma" body="3 milestones · 21 dias úteis" />
        <Block n="05" t="Investimento" body="R$ 4.000 · 50/50" />
        <Block n="06" t="Próximos passos" body="Aceite + assinatura digital" />
        <button className="kp-btn" style={{ alignSelf: "start" }}>+ Adicionar bloco</button>
      </div>

      {/* Live preview */}
      <div>
        <div className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.2em", color: "var(--kp-muted)", marginBottom: 8 }}>
          PREVIEW · TEMPLATE: <strong style={{ fontFamily: "var(--kp-display)", fontStyle: "italic", letterSpacing: 0, fontSize: 13 }}>{TEMPLATES.find(t=>t.id===tpl)?.name}</strong>
        </div>
        <TemplateMini id={tpl} />
      </div>
    </div>
  );
}

function Block({ n, t, body }) {
  return (
    <div className="kp-card kp-card-soft" style={{ padding: "14px 16px", display: "flex", alignItems: "center", gap: 14 }}>
      <span className="kp-mono" style={{ width: 32, height: 32, background: "var(--kp-ink)", color: "var(--kp-paper)", display: "inline-flex", alignItems: "center", justifyContent: "center", fontSize: 10 }}>{n}</span>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 14, fontWeight: 500 }}>{t}</div>
        <div style={{ fontSize: 12, color: "var(--kp-muted)" }}>{body}</div>
      </div>
      <button className="kp-btn kp-btn-sm">Editar</button>
    </div>
  );
}

// ─── Templates gallery ──────────────────────────────────
function Templates({ tpl, setTpl }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 18 }}>
      {TEMPLATES.map(t => (
        <div key={t.id} className="kp-card" style={{
          padding: 0, overflow: "hidden", cursor: "pointer",
          boxShadow: tpl === t.id ? "6px 6px 0 0 var(--kp-pink)" : "4px 4px 0 0 var(--kp-ink)",
          outline: tpl === t.id ? "2px solid var(--kp-pink)" : "none",
          outlineOffset: "-2px",
        }} onClick={()=>setTpl(t.id)}>
          <div style={{ height: 220, background: t.accent, borderBottom: "1.5px solid var(--kp-ink)", padding: 16, overflow: "hidden", position: "relative" }}>
            <TemplateMini id={t.id} small />
          </div>
          <div style={{ padding: 16 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 4 }}>
              <h3 className="kp-display" style={{ fontSize: 22, lineHeight: 1.1 }}>{t.name}</h3>
              {tpl === t.id && <span className="status-chip status-chip--accept">Selecionado</span>}
            </div>
            <p style={{ fontSize: 12.5, color: "var(--kp-muted)", margin: "4px 0 10px" }}>{t.sub}</p>
            <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
              {t.tags.map(tag => (
                <span key={tag} className="kp-mono" style={{ fontSize: 9, letterSpacing: "0.14em", padding: "3px 7px", border: "1.5px solid var(--kp-ink)", background: "var(--kp-soft)" }}>{tag}</span>
              ))}
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}

// ─── Mini renderings of each template ───────────────────
function TemplateMini({ id, small }) {
  if (id === "kaleidos") {
    return (
      <div style={{ background: "var(--kp-paper)", border: "1.5px solid var(--kp-ink)", padding: small ? 12 : 22, height: small ? "100%" : 460, overflow: "hidden", boxShadow: small ? "none" : "4px 4px 0 0 var(--kp-ink)" }}>
        <div style={{ height: 4, background: "var(--kp-pink)", marginBottom: 14 }} />
        <span className="kp-eyebrow" style={{ fontSize: 7, padding: "3px 8px", boxShadow: "1px 1px 0 0 var(--kp-ink)" }}>Nº 01 · Proposta</span>
        <h2 className="kp-display" style={{ fontSize: small ? 18 : 36, lineHeight: 1.05, margin: "10px 0 8px" }}>
          Módulo de <em>Agendamento</em><br/>com <span className="kp-splash" style={{ fontSize: small ? 17 : 35 }}>IA</span>.
        </h2>
        <p style={{ fontSize: small ? 9 : 13, color: "var(--kp-muted)", margin: 0 }}>Para Diogo Costa · Costa & Filhos</p>
        {!small && (
          <>
            <hr style={{ border: "none", borderTop: "1.5px solid var(--kp-ink)", margin: "16px 0" }} />
            <p style={{ fontSize: 13, lineHeight: 1.55, margin: 0 }}>
              Com base nas evoluções discutidas, estruturamos este módulo para permitir que o agente avance além da qualificação.
            </p>
            <div style={{ marginTop: 16, padding: 12, background: "var(--kp-ink)", color: "var(--kp-paper)" }}>
              <div className="kp-mono" style={{ fontSize: 9, letterSpacing: "0.2em", color: "var(--kp-faint)" }}>VALOR</div>
              <div className="kp-display" style={{ fontSize: 32, fontStyle: "italic", lineHeight: 1, marginTop: 4 }}>R$ 4.000,00</div>
            </div>
          </>
        )}
      </div>
    );
  }
  if (id === "minimal") {
    return (
      <div style={{ background: "#FAFAFA", border: "1px solid #111", padding: small ? 12 : 28, height: small ? "100%" : 460, overflow: "hidden", fontFamily: "Inter, sans-serif" }}>
        <div style={{ display: "flex", justifyContent: "space-between", fontFamily: "JetBrains Mono", fontSize: small ? 7 : 9, color: "#666", letterSpacing: "0.1em", textTransform: "uppercase" }}>
          <span>Proposal · 0042</span><span>Apr 2026</span>
        </div>
        <h2 style={{ fontSize: small ? 16 : 32, fontWeight: 600, lineHeight: 1.1, margin: small ? "16px 0 8px" : "40px 0 14px", letterSpacing: "-0.02em" }}>Módulo de Agendamento com IA</h2>
        <p style={{ fontSize: small ? 8.5 : 12, color: "#666", margin: 0 }}>Diogo Costa · Costa & Filhos Imóveis</p>
        {!small && (
          <>
            <table style={{ width: "100%", marginTop: 32, borderCollapse: "collapse", fontSize: 12 }}>
              {[["Setup", "R$ 1.500"],["Desenvolvimento", "R$ 1.800"],["QA + entrega", "R$ 700"],["Total", "R$ 4.000"]].map((r,i,a) => (
                <tr key={r[0]} style={{ borderTop: "1px solid #E5E5E5", borderBottom: i === a.length-1 ? "2px solid #111" : "none" }}>
                  <td style={{ padding: "10px 0", fontWeight: i === a.length-1 ? 600 : 400 }}>{r[0]}</td>
                  <td style={{ padding: "10px 0", textAlign: "right", fontFamily: "JetBrains Mono", fontWeight: i === a.length-1 ? 600 : 400 }}>{r[1]}</td>
                </tr>
              ))}
            </table>
          </>
        )}
      </div>
    );
  }
  // soft
  return (
    <div style={{ background: "#FFF6F0", border: "1px solid #E8C7B5", borderRadius: 18, padding: small ? 12 : 28, height: small ? "100%" : 460, overflow: "hidden", fontFamily: "'Instrument Serif', Georgia, serif" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: small ? 12 : 22 }}>
        <span style={{ width: small ? 10 : 14, height: small ? 10 : 14, borderRadius: "50%", background: "#E89B72" }} />
        <span style={{ fontSize: small ? 8 : 11, color: "#A57760", letterSpacing: "0.12em", textTransform: "uppercase", fontFamily: "Inter" }}>Studio · proposta</span>
      </div>
      <h2 style={{ fontSize: small ? 18 : 38, lineHeight: 1.1, margin: 0, color: "#3D2A1E", fontStyle: "italic" }}>Módulo de Agendamento com IA</h2>
      <p style={{ fontSize: small ? 9 : 14, color: "#A57760", marginTop: 8, fontFamily: "Inter" }}>Para Diogo Costa</p>
      {!small && (
        <>
          <p style={{ fontSize: 14, lineHeight: 1.6, color: "#5A4030", marginTop: 24, fontFamily: "Inter" }}>
            Estruturamos este módulo para que o agente avance além da qualificação. Conduzindo o lead até o agendamento, com calma e precisão.
          </p>
          <div style={{ marginTop: 24, padding: 18, background: "#F4D9C7", borderRadius: 12, color: "#3D2A1E" }}>
            <div style={{ fontSize: 10, color: "#A57760", letterSpacing: "0.1em", textTransform: "uppercase", fontFamily: "Inter" }}>Investimento</div>
            <div style={{ fontSize: 30, fontStyle: "italic", lineHeight: 1, marginTop: 4 }}>R$ 4.000</div>
          </div>
        </>
      )}
    </div>
  );
}

// ─── Anexos / PDFs ──────────────────────────────────────
function Anexos({ files, onUpload, fileRef, setFiles }) {
  const [drag, setDrag] = React.useState(false);
  const onDrop = (e) => {
    e.preventDefault(); setDrag(false);
    const list = Array.from(e.dataTransfer.files || []);
    const adds = list.map(f => ({
      name: f.name, size: (f.size/1024/1024 < 1 ? Math.round(f.size/1024)+"KB" : (f.size/1024/1024).toFixed(1)+"MB"),
      views: 0, kind: f.name.match(/\.(jpg|jpeg|png|webp|gif)$/i) ? "img" : f.name.match(/\.pdf$/i) ? "pdf" : "doc",
    }));
    setFiles([...adds, ...files]);
  };
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1.2fr 1fr", gap: 20 }}>
      <div>
        <div onDragOver={(e)=>{e.preventDefault();setDrag(true);}} onDragLeave={()=>setDrag(false)} onDrop={onDrop}
          onClick={()=>fileRef.current?.click()}
          style={{
            padding: 36, textAlign: "center", cursor: "pointer",
            border: "2px dashed " + (drag ? "var(--kp-pink)" : "var(--kp-ink)"),
            background: drag ? "var(--kp-pink-soft)" : "var(--kp-white)",
          }}>
          <div className="kp-display" style={{ fontSize: 28, lineHeight: 1.1 }}>Arraste PDFs, imagens ou docs <em>aqui.</em></div>
          <p style={{ fontSize: 13, color: "var(--kp-muted)", marginTop: 8 }}>Ou clique pra selecionar. Cada anexo vira parte do tracking — saberemos quando o cliente abrir.</p>
          <input ref={fileRef} type="file" multiple onChange={onUpload} hidden />
          <div style={{ marginTop: 16, display: "inline-flex", gap: 8 }}>
            <span className="kp-mono" style={{ fontSize: 9, letterSpacing: "0.16em", padding: "4px 8px", border: "1.5px solid var(--kp-ink)", background: "var(--kp-soft)" }}>PDF</span>
            <span className="kp-mono" style={{ fontSize: 9, letterSpacing: "0.16em", padding: "4px 8px", border: "1.5px solid var(--kp-ink)", background: "var(--kp-soft)" }}>PNG · JPG</span>
            <span className="kp-mono" style={{ fontSize: 9, letterSpacing: "0.16em", padding: "4px 8px", border: "1.5px solid var(--kp-ink)", background: "var(--kp-soft)" }}>XLSX · DOCX</span>
            <span className="kp-mono" style={{ fontSize: 9, letterSpacing: "0.16em", padding: "4px 8px", border: "1.5px solid var(--kp-ink)", background: "var(--kp-soft)" }}>até 50MB</span>
          </div>
        </div>

        <div style={{ marginTop: 20 }}>
          <div className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.2em", color: "var(--kp-muted)", marginBottom: 10 }}>ANEXOS · {files.length}</div>
          <div className="kp-card" style={{ padding: 0 }}>
            {files.map((f, i) => (
              <div key={i} style={{
                display: "grid", gridTemplateColumns: "auto 1fr auto auto auto",
                gap: 14, alignItems: "center",
                padding: "12px 16px",
                borderBottom: i === files.length-1 ? "none" : "1px solid rgba(10,10,10,0.1)",
              }}>
                <span className="kp-mono" style={{ fontSize: 9, letterSpacing: "0.14em", padding: "4px 8px", background: f.kind === "pdf" ? "var(--kp-pink)" : f.kind === "img" ? "var(--kp-cold)" : "var(--kp-warm)", border: "1.5px solid var(--kp-ink)" }}>{f.kind.toUpperCase()}</span>
                <span style={{ fontSize: 13, fontWeight: 500, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{f.name}</span>
                <span className="kp-mono" style={{ fontSize: 10, color: "var(--kp-muted)", letterSpacing: "0.1em" }}>{f.size}</span>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 4, fontSize: 12, color: f.views > 0 ? "var(--kp-ink)" : "var(--kp-faint)" }}>
                  <Icon.eye s={12} /> {f.views}
                </span>
                <button className="kp-btn kp-btn-sm" style={{ padding: "5px 10px" }}>···</button>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Activity feed for attachments */}
      <div>
        <div className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.2em", color: "var(--kp-muted)", marginBottom: 10 }}>ATIVIDADE EM ANEXOS</div>
        <div className="kp-card" style={{ padding: 0 }}>
          {[
            { f: "moodboard-v2.png", a: "Cliente abriu", t: "30 abr · 17:42", k: "view" },
            { f: "moodboard-v2.png", a: "Cliente baixou", t: "30 abr · 17:43", k: "down" },
            { f: "briefing-cliente.pdf", a: "Cliente abriu", t: "28 abr · 19:14", k: "view" },
            { f: "briefing-cliente.pdf", a: "Encaminhado por e-mail", t: "28 abr · 19:18", k: "share" },
            { f: "cronograma.xlsx", a: "Cliente abriu", t: "27 abr · 11:30", k: "view" },
          ].map((r, i) => (
            <div key={i} style={{ padding: "12px 16px", borderBottom: i === 4 ? "none" : "1px solid rgba(10,10,10,0.1)", display: "flex", gap: 12, alignItems: "start" }}>
              <span style={{
                width: 24, height: 24, flexShrink: 0,
                background: r.k === "view" ? "var(--kp-cold)" : r.k === "down" ? "var(--kp-green)" : "var(--kp-pink)",
                border: "1.5px solid var(--kp-ink)",
                display: "inline-flex", alignItems: "center", justifyContent: "center",
              }}>
                {r.k === "view" ? <Icon.eye s={12}/> : r.k === "down" ? <Icon.arrow s={12}/> : <Icon.send s={12}/>}
              </span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13 }}><strong>{r.a}</strong> <span style={{ color: "var(--kp-muted)" }}>· {r.f}</span></div>
                <div className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.16em", color: "var(--kp-faint)", marginTop: 4 }}>{r.t}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ─── Envio + tracking ───────────────────────────────────
function Envio() {
  const [clientes, setClientes] = React.useState([]);
  const [produtos, setProdutos] = React.useState([]);
  const [clientId, setClientId] = React.useState("");
  const [productId, setProductId] = React.useState("");
  const [title, setTitle] = React.useState("");
  const [valor, setValor] = React.useState("");
  const [paymentTerms, setPaymentTerms] = React.useState("Único · 7 dias");
  const [intro, setIntro] = React.useState("");
  const [submitting, setSubmitting] = React.useState(false);
  const [feedback, setFeedback] = React.useState(null);

  React.useEffect(() => {
    window.SEQ_API.listClients()
      .then(d => setClientes(d.clients || []))
      .catch(() => {});
    window.SEQ_API.listProducts()
      .then(d => setProdutos(d.products || []))
      .catch(() => {});
  }, []);

  // Auto-popula título/valor/condições quando seleciona um produto
  React.useEffect(() => {
    if (!productId) return;
    const prod = produtos.find(p => p.id === productId);
    if (prod) {
      if (!title) setTitle(prod.name);
      if (!valor) setValor(((prod.price ?? 0) / 100).toFixed(2).replace(".", ","));
      if (prod.billingCycle && prod.billingCycle !== "once") {
        const map = { weekly: "Recorrente · semanal", monthly: "Recorrente · mensal", quarterly: "Recorrente · trimestral", yearly: "Recorrente · anual" };
        setPaymentTerms(map[prod.billingCycle] || "Recorrente");
      } else {
        setPaymentTerms("Único · 7 dias");
      }
    }
  }, [productId, produtos]);

  const selectedProduct = productId ? produtos.find(p => p.id === productId) : null;
  const isRecurringProduct = selectedProduct && selectedProduct.billingCycle && selectedProduct.billingCycle !== "once";

  async function criarProposta() {
    if (!clientId || !title || !valor) {
      setFeedback({ type: "error", msg: "Preencha cliente, título e valor." });
      return;
    }
    setSubmitting(true);
    setFeedback(null);
    try {
      const cents = Math.round(parseFloat(valor.replace(",", ".").replace(/[^0-9.]/g, "")) * 100);
      const r = await window.SEQ_API.createProposal({
        clientId,
        productId: productId || undefined,
        title: title.trim(),
        intro: intro.trim() || undefined,
        totalAmount: cents,
        paymentTerms,
      });
      try { await window.SEQ_API.sendProposal(r.proposal.id); } catch {}
      setFeedback({ type: "success", msg: isRecurringProduct
        ? "✓ Proposta criada · ao aceitar gera assinatura recorrente Asaas."
        : "✓ Proposta criada e marcada como enviada."
      });
      setTimeout(() => {
        window.location.hash = `/proposta?id=${r.proposal.id}`;
      }, 800);
    } catch (err) {
      setFeedback({ type: "error", msg: err.message || "Falha ao criar." });
      setSubmitting(false);
    }
  }

  return (
    <div style={{ display: "grid", gridTemplateColumns: "1.2fr 1fr", gap: 20 }}>
      <div className="kp-card" style={{ padding: 24 }}>
        <div className="kp-display" style={{ fontSize: 24 }}>Crie e envie</div>
        <p style={{ fontSize: 13, color: "var(--kp-muted)", marginTop: 6 }}>Salva no banco e marca como enviada — gera link público e tracking automático.</p>

        <div style={{ marginTop: 18, display: "flex", flexDirection: "column", gap: 12 }}>
          <label>
            <span className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.18em", color: "var(--kp-muted)" }}>CLIENTE</span>
            <select value={clientId} onChange={e => setClientId(e.target.value)} className="kp-input" style={{ marginTop: 6 }}>
              <option value="">{clientes.length ? "Selecione um cliente" : "Crie um cliente em /clientes primeiro"}</option>
              {clientes.map(c => <option key={c.id} value={c.id}>{c.name} {c.company ? `(${c.company})` : ""}</option>)}
            </select>
          </label>
          <label>
            <span className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.18em", color: "var(--kp-muted)" }}>
              PRODUTO (OPCIONAL) {isRecurringProduct && <em style={{ color: "var(--kp-pink)", fontStyle: "italic", letterSpacing: 0, textTransform: "none" }}> · gera assinatura recorrente</em>}
            </span>
            <select value={productId} onChange={e => setProductId(e.target.value)} className="kp-input" style={{ marginTop: 6 }}>
              <option value="">— Sem produto (cobrança única) —</option>
              {produtos.map(p => {
                const labels = { monthly: "/mês", yearly: "/ano", quarterly: "/trim", weekly: "/sem", once: " único" };
                const cyc = labels[p.billingCycle] || "";
                return <option key={p.id} value={p.id}>{p.name} · R$ {((p.price ?? 0) / 100).toFixed(2)}{cyc}</option>;
              })}
            </select>
          </label>
          <label>
            <span className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.18em", color: "var(--kp-muted)" }}>TÍTULO DA PROPOSTA</span>
            <input className="kp-input" value={title} onChange={e => setTitle(e.target.value)} placeholder="Branding completo + identidade visual" style={{ marginTop: 6 }} />
          </label>
          <label>
            <span className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.18em", color: "var(--kp-muted)" }}>VALOR (R$)</span>
            <input className="kp-input" value={valor} onChange={e => setValor(e.target.value)} placeholder="4000,00" style={{ marginTop: 6 }} />
          </label>
          <label>
            <span className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.18em", color: "var(--kp-muted)" }}>CONDIÇÕES DE PAGAMENTO</span>
            <input className="kp-input" value={paymentTerms} onChange={e => setPaymentTerms(e.target.value)} placeholder="50% entrada + 50% entrega" style={{ marginTop: 6 }} />
          </label>
          <label>
            <span className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.18em", color: "var(--kp-muted)" }}>INTRO (OPCIONAL)</span>
            <textarea className="kp-input" value={intro} onChange={e => setIntro(e.target.value)} rows={3} placeholder="Contexto de 1-2 linhas que aparece no topo da proposta..." style={{ marginTop: 6, resize: "vertical" }} />
          </label>
        </div>

        {feedback && (
          <div style={{ marginTop: 14, padding: "8px 12px", background: feedback.type === "success" ? "var(--kp-green)" : "#FFB5B5", border: "1.5px solid var(--kp-ink)", fontFamily: "var(--kp-mono)", fontSize: 10, letterSpacing: "0.14em" }}>{feedback.msg}</div>
        )}

        <button onClick={criarProposta} disabled={submitting} className="kp-btn kp-btn-ink" style={{ marginTop: 20, width: "100%", padding: "14px 18px", fontSize: 11 }}>
          {submitting ? "Criando proposta..." : "Criar e enviar →"}
        </button>
      </div>

      <div>
        <div className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.2em", color: "var(--kp-muted)", marginBottom: 10 }}>O QUE VAI ACONTECER</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          {[
            { t: "Proposta salva no Neon", d: "Title, valor, cliente, condições — tudo persistido em proposals." },
            { t: "Link público gerado", d: "pay.kaleidos.com.br/p/[slug] — cliente abre e o tracking começa." },
            { t: "Tracking de leitura", d: "Heartbeat 15s, tempo total, número de aberturas, IP, dispositivo." },
            { t: "Aceite digital", d: "Cliente preenche nome+email, aceita, status muda pra 'accepted'." },
          ].map((it, i) => (
            <div key={i} className="kp-card kp-card-soft" style={{ padding: 16 }}>
              <div className="kp-display" style={{ fontSize: 18 }}>{it.t}</div>
              <p style={{ fontSize: 13, color: "var(--kp-muted)", margin: "4px 0 0", lineHeight: 1.5 }}>{it.d}</p>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// Antigo Envio com configuração de canais (mantido caso queira reativar)
function _EnvioOld() {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1.2fr 1fr", gap: 20 }}>
      <div className="kp-card" style={{ padding: 24 }}>
        <div className="kp-display" style={{ fontSize: 24 }}>Como você quer enviar?</div>
        <p style={{ fontSize: 13, color: "var(--kp-muted)", marginTop: 6 }}>Cada canal recebe um link único — sabemos por onde o cliente abriu.</p>

        <div style={{ marginTop: 20, display: "flex", flexDirection: "column", gap: 10 }}>
          {[
            { k: "E-mail", icon: <Icon.mail/>, on: true, sub: "diogo@costaefilhos.com.br" },
            { k: "WhatsApp", icon: <Icon.whatsapp/>, on: true, sub: "+55 11 98765-4321" },
            { k: "Link copiável", icon: <Icon.link/>, on: false, sub: "sequencia.app/p/agendamento-ia-7Yh3xk" },
          ].map(c => (
            <label key={c.k} style={{ display: "flex", gap: 12, alignItems: "center", padding: 14, border: "1.5px solid var(--kp-ink)", background: c.on ? "var(--kp-green)" : "var(--kp-white)", cursor: "pointer" }}>
              <input type="checkbox" defaultChecked={c.on} style={{ width: 16, height: 16 }} />
              <span style={{
                width: 28, height: 28, background: "var(--kp-white)", border: "1.5px solid var(--kp-ink)",
                display: "inline-flex", alignItems: "center", justifyContent: "center",
              }}>{c.icon}</span>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 500 }}>{c.k}</div>
                <div style={{ fontSize: 12, color: "var(--kp-ink)", opacity: 0.7 }}>{c.sub}</div>
              </div>
            </label>
          ))}
        </div>

        <div style={{ marginTop: 22 }}>
          <div className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.18em", color: "var(--kp-muted)" }}>FOLLOW-UP AUTOMÁTICO</div>
          <div style={{ marginTop: 8, padding: 14, border: "1.5px dashed rgba(10,10,10,0.3)", background: "var(--kp-soft)" }}>
            <p style={{ fontSize: 13, lineHeight: 1.5, margin: 0 }}>
              <em>Se</em> não abrir em <strong>48h</strong>, mando lembrete automático.<br/>
              <em>Se</em> abrir e voltar 3x sem fechar, te aviso pra ligar.
            </p>
          </div>
        </div>

        <button className="kp-btn kp-btn-ink" style={{ marginTop: 24, width: "100%" }}>Enviar agora →</button>
      </div>

      <div>
        <div className="kp-mono" style={{ fontSize: 9.5, letterSpacing: "0.2em", color: "var(--kp-muted)", marginBottom: 10 }}>O QUE A IA VAI MONITORAR</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          {[
            { t: "Aberturas e re-leituras", d: "Cada acesso vira evento. Saberemos quando, de onde e por quanto tempo." },
            { t: "Scroll por seção", d: "Quanto tempo na proposta, quanto na seção de preço, quanto no cronograma." },
            { t: "Compartilhamentos internos", d: "Se o lead encaminhar pra um sócio, detectamos novo IP e te avisamos." },
            { t: "Aberturas dos PDFs anexos", d: "Cada PDF tem tracking individual — você sabe se o briefing foi lido." },
          ].map((it, i) => (
            <div key={i} className="kp-card kp-card-soft" style={{ padding: 16 }}>
              <div className="kp-display" style={{ fontSize: 18 }}>{it.t}</div>
              <p style={{ fontSize: 13, color: "var(--kp-muted)", margin: "4px 0 0", lineHeight: 1.5 }}>{it.d}</p>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

window.SEQ_EDITOR = Editor;
