/* global React, ReactDOM, TweaksPanel, TweakSection, TweakRadio, TweakSelect, TweakColor, TweakToggle, useTweaks */
const { useState, useEffect, useMemo, useRef, useCallback } = React;

/* ---------- TWEAKS ---------- */
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": "veddu",
  "headingFont": "Bricolage Grotesque",
  "density": "comfortable",
  "showProgress": true,
  "mode": "guided"
}/*EDITMODE-END*/;

const PALETTES = {
  veddu:     { bg: "oklch(97.5% 0.005 80)",  ink: "oklch(20% 0.11 270)",   accent: "oklch(70% 0.17 55)",  accent2: "oklch(60% 0.20 30)",  muted: "oklch(55% 0.04 270)", line: "oklch(90% 0.012 270)", soft: "oklch(96% 0.012 270)" },
  linen:     { bg: "oklch(97.5% 0.008 85)",  ink: "oklch(22% 0.012 60)",   accent: "oklch(48% 0.11 235)", accent2: "oklch(60% 0.13 35)",  muted: "oklch(58% 0.012 70)", line: "oklch(89% 0.01 85)",   soft: "oklch(94% 0.012 85)" },
  midnight:  { bg: "oklch(18% 0.08 270)",    ink: "oklch(96% 0.01 80)",    accent: "oklch(72% 0.17 55)",  accent2: "oklch(62% 0.20 30)",  muted: "oklch(68% 0.03 270)", line: "oklch(28% 0.05 270)",  soft: "oklch(24% 0.07 270)" },
  graphite:  { bg: "oklch(96% 0.004 80)",    ink: "oklch(18% 0.005 80)",   accent: "oklch(28% 0.01 80)",  accent2: "oklch(50% 0.12 40)",  muted: "oklch(55% 0.008 80)", line: "oklch(86% 0.006 80)",  soft: "oklch(92% 0.008 80)" },
};

/* ---------- GOOGLE SHEETS ---------- */
const SHEETS_URL = "https://script.google.com/macros/s/AKfycbw2PQvyiVbx7QLEyDutMeyxL13xLrytNOFKLLcSE4fnwGV0-6Sg28KTekesYu5brzDE/exec";

/* ---------- HELPERS ---------- */
const STORAGE_KEY = "briefing.supplement.v1";
const SENT_KEY = "briefing.supplement.v1.sent";

function loadState() {
  try { return JSON.parse(localStorage.getItem(STORAGE_KEY) || "{}"); } catch { return {}; }
}
function saveState(s) {
  try { localStorage.setItem(STORAGE_KEY, JSON.stringify(s)); } catch {}
}
function markSent() {
  try { localStorage.setItem(SENT_KEY, new Date().toISOString()); } catch {}
}
function getSentDate() {
  try { return localStorage.getItem(SENT_KEY); } catch { return null; }
}

/* ---------- FIELD PRIMITIVES ---------- */
function Field({ label, hint, optional, children, full }) {
  return (
    <label className={"field" + (full ? " field--full" : "")}>
      <div className="field__head">
        <span className="field__label">{label}</span>
        {optional && <span className="field__opt">opcional</span>}
      </div>
      {hint && <span className="field__hint">{hint}</span>}
      <div className="field__control">{children}</div>
    </label>
  );
}

function TextField({ value, onChange, placeholder, multiline, rows = 3 }) {
  if (multiline) {
    return <textarea className="input input--area" rows={rows} value={value || ""} onChange={(e) => onChange(e.target.value)} placeholder={placeholder} />;
  }
  return <input className="input" type="text" value={value || ""} onChange={(e) => onChange(e.target.value)} placeholder={placeholder} />;
}

function CheckGroup({ options, value = [], onChange, otherKey = "outros", multiline = false }) {
  const toggle = (opt) => {
    const next = value.includes(opt) ? value.filter((v) => v !== opt) : [...value, opt];
    onChange(next);
  };
  return (
    <div className={"checkgrid" + (multiline ? " checkgrid--col" : "")}>
      {options.map((opt) => (
        <button type="button" key={opt} className={"chip" + (value.includes(opt) ? " chip--on" : "")} onClick={() => toggle(opt)}>
          <span className="chip__box" aria-hidden>{value.includes(opt) ? "✓" : ""}</span>
          <span className="chip__label">{opt}</span>
        </button>
      ))}
    </div>
  );
}

function RadioRow({ options, value, onChange }) {
  return (
    <div className="radiorow">
      {options.map((opt) => (
        <button type="button" key={opt} className={"radio" + (value === opt ? " radio--on" : "")} onClick={() => onChange(opt)}>
          <span className="radio__dot" aria-hidden />
          <span>{opt}</span>
        </button>
      ))}
    </div>
  );
}

const pendingFiles = new Map();

function AssetSlot({ label, hint, value, onChange, fieldKey }) {
  const inputRef = useRef(null);
  const has = Array.isArray(value) && value.length > 0;
  const onFiles = (files) => {
    const fileList = Array.from(files);
    const names = fileList.map((f) => f.name);
    fileList.forEach((f) => {
      const reader = new FileReader();
      reader.onload = () => {
        pendingFiles.set(fieldKey + "/" + f.name, {
          campo: label, nome: f.name, tipo: f.type,
          dados: reader.result.split(",")[1]
        });
      };
      reader.readAsDataURL(f);
    });
    onChange([...(value || []), ...names]);
  };
  const remove = (i) => {
    pendingFiles.delete(fieldKey + "/" + value[i]);
    onChange(value.filter((_, j) => j !== i));
  };
  return (
    <div className={"asset" + (has ? " asset--has" : "")}>
      <div className="asset__head">
        <div>
          <div className="asset__label">{label}</div>
          {hint && <div className="asset__hint">{hint}</div>}
        </div>
        <button type="button" className="asset__btn" onClick={() => inputRef.current?.click()}>
          {has ? "Adicionar mais" : "Anexar arquivos"}
        </button>
        <input ref={inputRef} type="file" multiple accept="image/*,video/*,.pdf,.svg" style={{ display: "none" }} onChange={(e) => onFiles(e.target.files)} />
      </div>
      {has ? (
        <ul className="asset__list">
          {value.map((n, i) => (
            <li key={i}>
              <span className="asset__name">{n}</span>
              <button type="button" className="asset__rm" onClick={() => remove(i)} aria-label="Remover">×</button>
            </li>
          ))}
        </ul>
      ) : (
        <div className="asset__drop">Arraste aqui ou clique em "Anexar arquivos"</div>
      )}
    </div>
  );
}

/* ---------- SECTIONS DEFINITION ---------- */
function SectionShell({ index, total, eyebrow, title, intro, children }) {
  return (
    <section className="section" data-screen-label={`${String(index).padStart(2, "0")} ${eyebrow}`}>
      <header className="section__head">
        <div className="section__meta">
          <span className="section__num">{String(index).padStart(2, "0")} / {String(total).padStart(2, "0")}</span>
          <span className="section__eyebrow">{eyebrow}</span>
        </div>
        <h2 className="section__title">{title}</h2>
        {intro && <p className="section__intro">{intro}</p>}
      </header>
      <div className="section__body">{children}</div>
    </section>
  );
}

/* ---------- SECTION 1: PRODUTO ---------- */
function ProdutoSection({ state, set, index, total }) {
  const v = state.produto || {};
  const u = (k, val) => set("produto", { ...v, [k]: val });
  return (
    <SectionShell index={index} total={total} eyebrow="Produto" title="Sobre o suplemento" intro="O essencial: o que é, para quem é e por que vale a pena. Quanto mais específico, mais convincente fica o copy.">
      <div className="grid grid--2">
        <Field label="Nome do produto"><TextField value={v.nome} onChange={(x) => u("nome", x)} placeholder="ex: Whey Isolado 90" /></Field>
        <Field label="Marca"><TextField value={v.marca} onChange={(x) => u("marca", x)} placeholder="ex: Nutrify" /></Field>
      </div>
      <Field label="Categoria do produto" hint="Ajuda a calibrar o tom da página">
        <CheckGroup
          options={["Whey / proteína", "Creatina", "Termogênico", "Colágeno", "Pré-treino", "Vitaminas / multi", "Emagrecedor", "Sono / relaxante", "Imunidade", "Outra"]}
          value={v.categoria || []}
          onChange={(x) => u("categoria", x)}
        />
      </Field>
      <Field label="Para quem é indicado" hint="Persona principal. Seja específico — 'mulheres 35–55 que treinam 3x/semana' converte melhor que 'todos'." full>
        <TextField multiline rows={2} value={v.publico} onChange={(x) => u("publico", x)} placeholder="ex: Mulheres acima de 40 anos, sedentárias, com queda capilar" />
      </Field>
      <Field label="Principal promessa" hint="A transformação central. Uma frase, sem rodeios." full>
        <TextField multiline rows={2} value={v.promessa} onChange={(x) => u("promessa", x)} placeholder="ex: Reduzir queda de cabelo em até 45 dias" />
      </Field>
      <Field label="Diferenciais vs. concorrência" hint="Liste 3 a 5 pontos que ninguém mais oferece" full>
        <TextField multiline rows={4} value={v.diferenciais} onChange={(x) => u("diferenciais", x)} placeholder={"• Único com fórmula X\n• Aprovado por...\n• 2x mais concentrado"} />
      </Field>
      <Field label="Composição / ingredientes principais" hint="Os que vão ser destacados no copy" full>
        <TextField multiline rows={3} value={v.composicao} onChange={(x) => u("composicao", x)} placeholder="ex: Biotina 5000mcg, MSM, Colágeno tipo I e III..." />
      </Field>
      <Field label="Certificações" hint="Marque tudo que se aplica">
        <CheckGroup
          options={["Anvisa", "Orgânico", "Vegano", "Sem glúten", "Sem lactose", "Não testado em animais", "Sem açúcar", "Kosher", "ISO / GMP"]}
          value={v.certificacoes || []}
          onChange={(x) => u("certificacoes", x)}
        />
      </Field>
      <div className="grid grid--2">
        <Field label="Sabores disponíveis" optional><TextField value={v.sabores} onChange={(x) => u("sabores", x)} placeholder="ex: Chocolate, Baunilha, Morango" /></Field>
        <Field label="Tamanhos / apresentações"><TextField value={v.tamanhos} onChange={(x) => u("tamanhos", x)} placeholder="ex: 30 cápsulas, 60 cápsulas, 900g" /></Field>
      </div>
    </SectionShell>
  );
}

/* ---------- SECTION 2: IDENTIDADE ---------- */
function IdentidadeSection({ state, set, index, total }) {
  const v = state.identidade || {};
  const u = (k, val) => set("identidade", { ...v, [k]: val });
  return (
    <SectionShell index={index} total={total} eyebrow="Identidade Visual" title="Materiais visuais" intro="Reúna tudo que já existe da marca. Se faltar algo, deixe em branco — produzimos junto.">
      <AssetSlot label="Logo" hint="PNG ou SVG, fundo transparente. Versão horizontal e ícone, se tiver." value={v.logo} onChange={(x) => u("logo", x)} fieldKey="identidade.logo" />
      <AssetSlot label="Fotos do produto" hint="Embalagem em vários ângulos. Mín. 1500px no lado maior." value={v.fotosProduto} onChange={(x) => u("fotosProduto", x)} fieldKey="identidade.fotosProduto" />
      <AssetSlot label="Fotos lifestyle / pessoas usando" hint="Pessoas reais usando o produto. Aumenta conversão." value={v.fotosLifestyle} onChange={(x) => u("fotosLifestyle", x)} fieldKey="identidade.fotosLifestyle" />
      <div className="grid grid--2">
        <Field label="Paleta de cores existente" optional hint="Códigos hex ou descrição">
          <TextField multiline rows={2} value={v.paleta} onChange={(x) => u("paleta", x)} placeholder="ex: #0E3B2E, #F4EFE6, #C9A14A" />
        </Field>
        <Field label="Fontes da marca" optional>
          <TextField value={v.fontes} onChange={(x) => u("fontes", x)} placeholder="ex: Söhne (títulos) + Inter (corpo)" />
        </Field>
      </div>
      <AssetSlot label="Antes / depois" hint="Apenas se permitido pela Anvisa para a categoria do seu produto." value={v.antesDepois} onChange={(x) => u("antesDepois", x)} fieldKey="identidade.antesDepois" />
      <AssetSlot label="Vídeos (produto, depoimentos, anúncios)" hint="Aceitamos links do Drive, YouTube, WeTransfer." value={v.videos} onChange={(x) => u("videos", x)} fieldKey="identidade.videos" />
      <Field label="Links / referências de vídeo externos" optional full>
        <TextField multiline rows={2} value={v.linksVideo} onChange={(x) => u("linksVideo", x)} placeholder="Cole URLs do Drive, YouTube, etc." />
      </Field>
    </SectionShell>
  );
}

/* ---------- SECTION 3: PROVA SOCIAL ---------- */
function ProvaSocialSection({ state, set, index, total }) {
  const v = state.prova || {};
  const u = (k, val) => set("prova", { ...v, [k]: val });
  return (
    <SectionShell index={index} total={total} eyebrow="Prova Social" title="Quem já comprou e o que falaram" intro="Depoimentos e números reais são o que mais influenciam a decisão. Quanto mais, melhor.">
      <Field label="Depoimentos em texto" hint="Cole no formato: Nome — depoimento. Um por linha." full>
        <TextField multiline rows={6} value={v.depoimentosTexto} onChange={(x) => u("depoimentosTexto", x)}
          placeholder={"Maria, 42 — 'Em 30 dias minha unha parou de descascar.'\nJoão, 35 — 'Voltei a treinar todos os dias.'"} />
      </Field>
      <AssetSlot label="Fotos / vídeos de clientes" hint="Com autorização de uso de imagem." value={v.depoimentosMidia} onChange={(x) => u("depoimentosMidia", x)} fieldKey="prova.depoimentosMidia" />
      <div className="grid grid--3">
        <Field label="Nº de clientes atendidos" optional><TextField value={v.numClientes} onChange={(x) => u("numClientes", x)} placeholder="ex: +12.000" /></Field>
        <Field label="Nº de unidades vendidas" optional><TextField value={v.numVendas} onChange={(x) => u("numVendas", x)} placeholder="ex: 30 mil potes" /></Field>
        <Field label="Nota / avaliação média" optional><TextField value={v.avaliacao} onChange={(x) => u("avaliacao", x)} placeholder="ex: 4.9 / 5 — Google" /></Field>
      </div>
      <Field label="Influenciadores ou parceiros que usam" optional full>
        <TextField multiline rows={2} value={v.influencers} onChange={(x) => u("influencers", x)} placeholder="@perfil — segmento — link do post" />
      </Field>
      <Field label="Links de avaliações públicas" optional hint="Reclame Aqui, Google Meu Negócio, marketplaces" full>
        <TextField multiline rows={2} value={v.linksAvaliacoes} onChange={(x) => u("linksAvaliacoes", x)} placeholder="https://..." />
      </Field>
    </SectionShell>
  );
}

/* ---------- SECTION 4: OFERTA ---------- */
function OfertaSection({ state, set, index, total }) {
  const v = state.oferta || {};
  const u = (k, val) => set("oferta", { ...v, [k]: val });
  return (
    <SectionShell index={index} total={total} eyebrow="Oferta" title="Preço, kits e pagamento" intro="Como a venda acontece. Detalhe os kits para podermos destacar o melhor custo-benefício.">
      <div className="grid grid--2">
        <Field label="Preço cheio (de)"><TextField value={v.precoCheio} onChange={(x) => u("precoCheio", x)} placeholder="ex: R$ 297,00" /></Field>
        <Field label="Preço com desconto (por)"><TextField value={v.precoDesconto} onChange={(x) => u("precoDesconto", x)} placeholder="ex: R$ 197,00" /></Field>
      </div>
      <Field label="Formas de pagamento aceitas">
        <CheckGroup
          options={["Cartão à vista", "Cartão parcelado", "PIX", "Boleto", "PayPal", "Apple Pay / Google Pay"]}
          value={v.pagamentos || []} onChange={(x) => u("pagamentos", x)} />
      </Field>
      <Field label="Parcelamento máximo" optional><TextField value={v.parcelas} onChange={(x) => u("parcelas", x)} placeholder="ex: 12x sem juros" /></Field>
      <Field label="Plataforma de vendas">
        <RadioRow options={["Hotmart", "Kiwify", "Eduzz", "Shopify", "Loja própria", "WhatsApp", "Outra"]} value={v.plataforma} onChange={(x) => u("plataforma", x)} />
      </Field>
      <Field label="Link do checkout" full><TextField value={v.checkout} onChange={(x) => u("checkout", x)} placeholder="https://pay.hotmart.com/..." /></Field>
      <div className="grid grid--2">
        <Field label="Política de frete">
          <RadioRow options={["Grátis sempre", "Grátis acima de R$ X", "Cobrado", "Sem frete (digital)"]} value={v.frete} onChange={(x) => u("frete", x)} />
        </Field>
        <Field label="Valor mínimo p/ frete grátis" optional><TextField value={v.freteMin} onChange={(x) => u("freteMin", x)} placeholder="ex: R$ 199" /></Field>
      </div>
      <Field label="Kits oferecidos" hint="Descreva cada combinação que aparece na página" full>
        <TextField multiline rows={4} value={v.kits} onChange={(x) => u("kits", x)} placeholder={"Kit 1 — 1 pote — R$ 197\nKit 2 — 3 potes — R$ 497 (mais vendido)\nKit 3 — 6 potes — R$ 897"} />
      </Field>
      <div className="grid grid--2">
        <Field label="Garantia"><TextField value={v.garantia} onChange={(x) => u("garantia", x)} placeholder="ex: 30 dias incondicional" /></Field>
        <Field label="Bônus / brindes" optional><TextField value={v.bonus} onChange={(x) => u("bonus", x)} placeholder="ex: e-book + grupo VIP" /></Field>
      </div>
    </SectionShell>
  );
}

/* ---------- SECTION 5: ENTREGA ---------- */
function EntregaSection({ state, set, index, total }) {
  const v = state.entrega || {};
  const u = (k, val) => set("entrega", { ...v, [k]: val });
  return (
    <SectionShell index={index} total={total} eyebrow="Entrega e Confiança" title="Logística e dados legais" intro="Itens obrigatórios para o rodapé e seções de segurança. Sem isso a página não pode ir ao ar.">
      <div className="grid grid--2">
        <Field label="Prazo de entrega"><TextField value={v.prazo} onChange={(x) => u("prazo", x)} placeholder="ex: 3 a 7 dias úteis" /></Field>
        <Field label="Transportadora / Correios" optional><TextField value={v.transportadora} onChange={(x) => u("transportadora", x)} placeholder="ex: Correios + Jadlog" /></Field>
      </div>
      <Field label="Selos de segurança a exibir">
        <CheckGroup
          options={["Compra segura", "SSL / pagamento criptografado", "Site verificado", "Reclame Aqui", "Selo Anvisa", "Selo Vegano", "Selo Cruelty Free"]}
          value={v.selos || []} onChange={(x) => u("selos", x)} />
      </Field>
      <Field label="Razão social" hint="Obrigatório no rodapé"><TextField value={v.razao} onChange={(x) => u("razao", x)} placeholder="ex: Nutrify Suplementos LTDA" /></Field>
      <Field label="CNPJ"><TextField value={v.cnpj} onChange={(x) => u("cnpj", x)} placeholder="00.000.000/0001-00" /></Field>
      <Field label="Endereço completo" full><TextField multiline rows={2} value={v.endereco} onChange={(x) => u("endereco", x)} placeholder="Rua, número, bairro, cidade, UF, CEP" /></Field>
      <div className="grid grid--2">
        <Field label="E-mail de contato"><TextField value={v.email} onChange={(x) => u("email", x)} placeholder="contato@..." /></Field>
        <Field label="WhatsApp / telefone"><TextField value={v.tel} onChange={(x) => u("tel", x)} placeholder="(11) 9 0000-0000" /></Field>
      </div>
      <Field label="Política de devolução / trocas" full>
        <TextField multiline rows={3} value={v.devolucao} onChange={(x) => u("devolucao", x)} placeholder="Resuma como funciona. Vamos formatar para a página." />
      </Field>
    </SectionShell>
  );
}

/* ---------- SECTION 6: ESTRATÉGIA ---------- */
function EstrategiaSection({ state, set, index, total }) {
  const v = state.estrategia || {};
  const u = (k, val) => set("estrategia", { ...v, [k]: val });
  return (
    <SectionShell index={index} total={total} eyebrow="Estratégia" title="Como a página vai trabalhar" intro="O destino do clique muda toda a estrutura. Esses campos definem o esqueleto da página.">
      <Field label="Objetivo principal da página">
        <RadioRow options={["Venda direta", "Lead (e-mail/WhatsApp)", "Agendamento", "Pré-venda"]} value={v.objetivo} onChange={(x) => u("objetivo", x)} />
      </Field>
      <Field label="Fontes de tráfego previstas">
        <CheckGroup
          options={["Meta Ads (Facebook/Instagram)", "Google Ads", "TikTok Ads", "YouTube Ads", "E-mail marketing", "Influenciadores", "Orgânico / SEO", "Direto / off-line"]}
          value={v.trafego || []} onChange={(x) => u("trafego", x)} />
      </Field>
      <Field label="Rastreamento já instalado?">
        <CheckGroup
          options={["Pixel do Meta", "Google Tag (GA4)", "Google Ads Tag", "TikTok Pixel", "Hotjar / Clarity", "Não tenho nada"]}
          value={v.tracking || []} onChange={(x) => u("tracking", x)} />
      </Field>
      <div className="grid grid--2">
        <Field label="Domínio">
          <RadioRow options={["Já tenho", "Quero comprar", "Não sei"]} value={v.dominio} onChange={(x) => u("dominio", x)} />
        </Field>
        <Field label="Hospedagem">
          <RadioRow options={["Já tenho", "Vocês cuidam", "Não sei"]} value={v.hospedagem} onChange={(x) => u("hospedagem", x)} />
        </Field>
      </div>
      <Field label="Domínio desejado / atual" optional><TextField value={v.dominioUrl} onChange={(x) => u("dominioUrl", x)} placeholder="ex: www.marca.com.br" /></Field>
      <Field label="Landing pages que você gosta" hint="Cole 2–4 links. Diga 1 frase do que admira em cada." full>
        <TextField multiline rows={4} value={v.referencias} onChange={(x) => u("referencias", x)} placeholder={"https://...  — gosto do uso de prova social no topo\nhttps://... — preço apresentado de forma clara"} />
      </Field>
    </SectionShell>
  );
}

/* ---------- SECTION 7: COPY ---------- */
function CopySection({ state, set, index, total }) {
  const v = state.copy || {};
  const u = (k, val) => set("copy", { ...v, [k]: val });
  return (
    <SectionShell index={index} total={total} eyebrow="Copy" title="Narrativa e argumentos" intro="Pode pular se já tiver um copywriter. Se não tiver, esses três campos cobrem 80% do texto da página.">
      <Field label="História da marca / fundador" hint="Como começou, por que existe. 1 a 2 parágrafos." full>
        <TextField multiline rows={5} value={v.historia} onChange={(x) => u("historia", x)} placeholder="Conte a origem como se estivesse explicando para um amigo." />
      </Field>
      <Field label="Dor principal que o produto resolve" hint="O incômodo do dia a dia. Use as palavras do cliente." full>
        <TextField multiline rows={4} value={v.dor} onChange={(x) => u("dor", x)} placeholder={"ex: cabelo caindo no travesseiro toda manhã, vergonha no espelho..."} />
      </Field>
      <Field label="Objeções mais comuns" hint="O que faz a pessoa hesitar. Vamos derrubar uma a uma." full>
        <TextField multiline rows={5} value={v.objecoes} onChange={(x) => u("objecoes", x)} placeholder={"• 'É caro demais'\n• 'Não vai funcionar comigo'\n• 'Vou ter que tomar pra sempre?'"} />
      </Field>
      <Field label="Tom de voz desejado">
        <CheckGroup options={["Acolhedor", "Técnico / científico", "Direto e forte", "Premium / elegante", "Divertido", "Motivacional"]} value={v.tom || []} onChange={(x) => u("tom", x)} />
      </Field>
      <Field label="Palavras / expressões PROIBIDAS" optional hint="Termos que a marca não usa nunca">
        <TextField value={v.banidas} onChange={(x) => u("banidas", x)} placeholder="ex: 'milagroso', 'cura', 'garantido'" />
      </Field>
    </SectionShell>
  );
}

/* ---------- COMPLETION HEURISTICS ---------- */
const SECTION_KEYS = ["produto", "identidade", "prova", "oferta", "entrega", "estrategia", "copy"];

function isFilled(v) {
  if (v === undefined || v === null) return false;
  if (typeof v === "string") return v.trim().length > 0;
  if (Array.isArray(v)) return v.length > 0;
  return Boolean(v);
}

function sectionProgress(state, key) {
  const v = state[key] || {};
  const fields = Object.values(v);
  if (fields.length === 0) return 0;
  const filled = fields.filter(isFilled).length;
  return filled;
}

/* ---------- CONTACT STRIP ---------- */
function ContactStrip({ variant }) {
  return (
    <div className={"contact" + (variant ? ` contact--${variant}` : "")}>
      <div className="contact__head">
        <span className="contact__eyebrow">Dúvidas durante o preenchimento?</span>
        <span className="contact__by">Veddu Digital</span>
      </div>
      <div className="contact__grid">
        <a className="contact__item" href="https://instagram.com/veddudigital" target="_blank" rel="noopener noreferrer">
          <span className="contact__label">Instagram</span>
          <span className="contact__value">@veddudigital</span>
        </a>
        <a className="contact__item" href="mailto:contato@veddu.com.br">
          <span className="contact__label">E-mail</span>
          <span className="contact__value">contato@veddu.com.br</span>
        </a>
        <a className="contact__item" href="https://wa.me/5511988204942" target="_blank" rel="noopener noreferrer">
          <span className="contact__label">WhatsApp</span>
          <span className="contact__value">(11) 98820-4942</span>
        </a>
      </div>
    </div>
  );
}

/* ---------- CUSTOM PALETTE PICKER (inline tweaks control) ---------- */
function PalettePicker({ value, onChange }) {
  const opts = [
    { key: "veddu",     label: "Veddu",     colors: ["oklch(70% 0.17 55)", "oklch(20% 0.11 270)",  "oklch(60% 0.20 30)"] },
    { key: "linen",     label: "Linen",     colors: ["oklch(48% 0.11 235)", "oklch(97.5% 0.008 85)", "oklch(22% 0.012 60)"] },
    { key: "midnight",  label: "Midnight",  colors: ["oklch(72% 0.17 55)", "oklch(18% 0.08 270)",  "oklch(62% 0.20 30)"] },
    { key: "graphite",  label: "Graphite",  colors: ["oklch(28% 0.01 80)",  "oklch(96% 0.004 80)",   "oklch(18% 0.005 80)"] },
  ];
  return (
    <div className="palette-picker">
      <div className="palette-picker__label">Paleta</div>
      <div className="palette-picker__grid">
        {opts.map((o) => (
          <button
            key={o.key}
            type="button"
            className={"palette-swatch" + (value === o.key ? " palette-swatch--on" : "")}
            onClick={() => onChange(o.key)}
            title={o.label}
          >
            <span className="palette-swatch__cols">
              {o.colors.map((c, i) => <span key={i} style={{ background: c }} />)}
            </span>
            <span className="palette-swatch__name">{o.label}</span>
          </button>
        ))}
      </div>
    </div>
  );
}

/* ---------- APP ---------- */
function BriefingApp() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [state, setState] = useState(() => loadState());
  const [step, setStep] = useState(0); // 0 = cover, 1..N = sections, N+1 = review
  const [dir, setDir] = useState(1);   // 1 forward, -1 back (for transition direction)
  const [sending, setSending] = useState(false);
  const [sent, setSent] = useState(() => !!getSentDate());
  const palette = PALETTES[t.palette] || PALETTES.linen;

  useEffect(() => { saveState(state); }, [state]);

  const set = useCallback((key, value) => {
    setState((s) => ({ ...s, [key]: value }));
  }, []);

  /* dynamic CSS variables */
  useEffect(() => {
    const r = document.documentElement;
    r.style.setProperty("--bg", palette.bg);
    r.style.setProperty("--ink", palette.ink);
    r.style.setProperty("--accent", palette.accent);
    r.style.setProperty("--accent2", palette.accent2 || palette.accent);
    r.style.setProperty("--muted", palette.muted);
    r.style.setProperty("--line", palette.line);
    r.style.setProperty("--soft", palette.soft);
    r.style.setProperty("--font-head", `"${t.headingFont}", Georgia, serif`);
    r.style.setProperty("--pad", t.density === "compact" ? "14px" : "20px");
    document.body.dataset.palette = t.palette;
  }, [palette, t.headingFont, t.density, t.palette]);

  const sections = [
    { key: "produto",     Comp: ProdutoSection,     label: "Produto",          time: "3 min" },
    { key: "identidade",  Comp: IdentidadeSection,  label: "Identidade Visual",time: "5 min" },
    { key: "prova",       Comp: ProvaSocialSection, label: "Prova Social",     time: "3 min" },
    { key: "oferta",      Comp: OfertaSection,      label: "Oferta",           time: "4 min" },
    { key: "entrega",     Comp: EntregaSection,     label: "Entrega",          time: "3 min" },
    { key: "estrategia",  Comp: EstrategiaSection,  label: "Estratégia",       time: "3 min" },
    { key: "copy",        Comp: CopySection,        label: "Copy",             time: "4 min" },
  ];

  const totalSections = sections.length;
  const totalSteps = totalSections + 2; // cover + sections + review

  const totals = useMemo(() => {
    let filled = 0;
    SECTION_KEYS.forEach((k) => {
      const v = state[k] || {};
      filled += Object.values(v).filter(isFilled).length;
    });
    return filled;
  }, [state]);

  const exportText = () => {
    const lines = [];
    lines.push("BRIEFING — LANDING PAGE DE SUPLEMENTO");
    lines.push("Gerado em " + new Date().toLocaleString("pt-BR"));
    lines.push("");
    sections.forEach(({ key, label }, i) => {
      lines.push(`${String(i + 1).padStart(2, "0")}. ${label.toUpperCase()}`);
      lines.push("".padEnd(48, "-"));
      const v = state[key] || {};
      Object.entries(v).forEach(([k, val]) => {
        if (!isFilled(val)) return;
        const value = Array.isArray(val) ? val.join(", ") : val;
        lines.push(`${k}: ${value}`);
      });
      lines.push("");
    });
    if (state.obs) { lines.push("OBSERVAÇÕES"); lines.push("".padEnd(48, "-")); lines.push(state.obs); }
    const blob = new Blob([lines.join("\n")], { type: "text/plain;charset=utf-8" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url; a.download = "briefing-suplemento.txt"; a.click();
    URL.revokeObjectURL(url);
  };

  const submitToSheets = async () => {
    if (SHEETS_URL.includes("__COLE_")) {
      alert("URL do Google Sheets ainda nao foi configurada.");
      return;
    }
    setSending(true);
    try {
      const payload = { ...state };
      if (pendingFiles.size > 0) {
        payload._arquivos = Array.from(pendingFiles.values());
      }
      await fetch(SHEETS_URL, {
        method: "POST",
        mode: "no-cors",
        headers: { "Content-Type": "text/plain" },
        body: JSON.stringify(payload),
      });
      markSent();
      setSent(true);
      alert("Briefing enviado com sucesso! A equipe Veddu Digital ja recebeu seus dados.");
    } catch (err) {
      alert("Erro ao enviar. Tente novamente ou exporte o .txt e envie por WhatsApp.");
    } finally {
      setSending(false);
    }
  };

  const resetAll = () => {
    if (confirm("Tem certeza que quer apagar todas as respostas?")) {
      setState({});
      setSent(false);
      setStep(0);
    }
  };

  const goTo = (n) => {
    const clamped = Math.max(0, Math.min(totalSteps - 1, n));
    setDir(clamped >= step ? 1 : -1);
    setStep(clamped);
  };
  const next = () => goTo(step + 1);
  const prev = () => goTo(step - 1);

  /* scroll to top whenever step changes */
  useEffect(() => {
    window.scrollTo(0, 0);
  }, [step]);

  /* keyboard nav */
  useEffect(() => {
    const onKey = (e) => {
      if (e.target.tagName === "INPUT" || e.target.tagName === "TEXTAREA") return;
      if (e.key === "ArrowRight") next();
      if (e.key === "ArrowLeft") prev();
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  });

  const guided = t.mode === "guided";

  /* SCROLL MODE — original list layout */
  if (!guided) {
    return (
      <div className="page">
        <div className="topbar">
          <div className="topbar__inner">
            <a className="brand" href="#" onClick={(e) => { e.preventDefault(); setStep(0); }}>
              <img src="assets/veddu-logo.png" alt="Veddu Digital" className="brand__logo" />
              <span className="brand__divider" aria-hidden />
              <span className="brand__doctype">Briefing · Landing Page</span>
            </a>
            <div className="topbar__actions">
              <button className="btn btn--ghost" onClick={resetAll}>Limpar</button>
              <button className="btn btn--ghost" onClick={() => window.print()}>Imprimir</button>
              <button className="btn btn--solid" onClick={exportText}>Exportar .txt</button>
            </div>
          </div>
        </div>
        <div className="layout">
          <main className="main">
            <header className="hero">
              <div className="hero__eyebrow"><span>Briefing</span><span className="dot" /><span>Modo lista</span></div>
              <h1 className="hero__title">Vamos construir a sua<br />landing page de suplemento.</h1>
              <p className="hero__lede">Tudo numa página só. Para o modo guiado, ative em Tweaks → Modo.</p>
            </header>
            {sections.map(({ Comp, key }, i) => (
              <div key={key}>
                <Comp state={state} set={set} index={i + 1} total={totalSections} />
              </div>
            ))}
            <section className="closing">
              <div className="closing__num">FIM</div>
              <h2 className="closing__title">Algo que esquecemos?</h2>
              <Field label="Observações livres" full>
                <TextField multiline rows={6} value={state.obs} onChange={(x) => set("obs", x)} />
              </Field>
              <div className="closing__actions">
                <button className="btn btn--solid btn--lg" onClick={submitToSheets} disabled={sending}>
                  {sending ? "Enviando..." : sent ? "Enviado! Reenviar" : "Enviar briefing para a Veddu"}
                </button>
                <button className="btn btn--ghost btn--lg" onClick={exportText}>Exportar .txt</button>
                <button className="btn btn--ghost btn--lg" onClick={() => window.print()}>Imprimir / PDF</button>
              </div>
              {sent && <p className="closing__sent">Briefing enviado em {new Date(getSentDate()).toLocaleString("pt-BR")}.</p>}
            </section>
          </main>
        </div>
        <TweaksPanelMount t={t} setTweak={setTweak} />
      </div>
    );
  }

  /* GUIDED MODE */
  const onCover = step === 0;
  const onReview = step === totalSteps - 1;
  const sectionIdx = step - 1; // -1 on cover, totalSections on review
  const activeSection = sections[sectionIdx];

  return (
    <div className="page page--guided">
      {/* Slim header */}
      <header className="ghead">
        <a className="ghead__brand" href="#" onClick={(e) => { e.preventDefault(); goTo(0); }}>
          <img src="assets/veddu-logo.png" alt="Veddu Digital" className="brand__logo" />
          <span className="brand__divider" aria-hidden />
          <span className="brand__doctype">Briefing</span>
        </a>
        <div className="ghead__center">
          {!onCover && !onReview && (
            <>
              <span className="ghead__step">Etapa {String(step).padStart(2, "0")} de {String(totalSections).padStart(2, "0")}</span>
              <span className="ghead__title">{activeSection.label}</span>
            </>
          )}
        </div>
        <div className="ghead__actions">
          <button className="btn btn--ghost btn--sm" onClick={resetAll}>Limpar</button>
        </div>
      </header>

      {/* Step bar */}
      {t.showProgress && !onCover && (
        <div className="stepbar">
          {sections.map((s, i) => {
            const filled = sectionProgress(state, s.key);
            const isOn = sectionIdx === i;
            const isPast = sectionIdx > i || onReview;
            return (
              <button
                key={s.key}
                type="button"
                className={"stepbar__seg" + (isOn ? " is-on" : "") + (isPast || filled > 0 ? " is-touched" : "")}
                onClick={() => goTo(i + 1)}
                aria-label={`Ir para ${s.label}`}
              >
                <span className="stepbar__num">{String(i + 1).padStart(2, "0")}</span>
                <span className="stepbar__label">{s.label}</span>
              </button>
            );
          })}
        </div>
      )}

      {/* Stage */}
      <div className="stage">
        <div className={"stage__inner stage__inner--dir-" + (dir > 0 ? "fwd" : "back")} key={step}>
          {onCover && (
            <section className="cover">
              <div className="cover__brandblock">
                <img src="assets/veddu-logo.png" alt="Veddu Digital" className="cover__logo" />
                <div className="cover__pixels" aria-hidden>
                  <span /><span /><span /><span /><span /><span /><span /><span /><span /><span /><span /><span />
                </div>
              </div>
              <div className="cover__eyebrow">
                <span>Briefing · v1.0</span>
                <span className="dot" />
                <span>~20 minutos no total</span>
                <span className="dot" />
                <span>Confidencial</span>
              </div>
              <h1 className="cover__title">
                Vamos construir a sua<br />
                <span className="cover__title-accent">landing page de suplemento</span>.
              </h1>
              <p className="cover__lede">
                Este formulário tem 7 etapas curtas. Em cada uma, pedimos algumas informações específicas sobre o seu produto, sua marca e sua oferta.
                Suas respostas são salvas automaticamente neste navegador — você pode fechar e voltar quando quiser.
              </p>
              <ol className="cover__list">
                {sections.map((s, i) => (
                  <li key={s.key}>
                    <span className="cover__list-num">{String(i + 1).padStart(2, "0")}</span>
                    <span className="cover__list-label">{s.label}</span>
                    <span className="cover__list-time">{s.time}</span>
                  </li>
                ))}
              </ol>
              <div className="cover__cta">
                <button className="btn btn--solid btn--lg" onClick={next}>Começar agora →</button>
                <span className="cover__hint">ou use ← → no teclado</span>
              </div>
              <ContactStrip />
            </section>
          )}

          {!onCover && !onReview && (
            <div className="stage__section">
              <activeSection.Comp state={state} set={set} index={step} total={totalSections} />
            </div>
          )}

          {onReview && (
            <section className="review">
              <div className="cover__eyebrow"><span>Última etapa</span></div>
              <h1 className="cover__title">Revisão e envio.</h1>
              <p className="cover__lede">
                Você preencheu {totals} campos. Antes de enviar, dê uma olhada no resumo e adicione qualquer observação final.
              </p>

              <div className="review__grid">
                {sections.map((s, i) => {
                  const filled = sectionProgress(state, s.key);
                  const v = state[s.key] || {};
                  const totalK = Math.max(Object.keys(v).length, 1);
                  return (
                    <button key={s.key} className="review__card" onClick={() => goTo(i + 1)}>
                      <div className="review__card-head">
                        <span className="review__card-num">{String(i + 1).padStart(2, "0")}</span>
                        <span className="review__card-status">{filled > 0 ? `${filled} preenchidos` : "vazio"}</span>
                      </div>
                      <div className="review__card-label">{s.label}</div>
                      <div className="review__card-bar"><span style={{ width: `${Math.min(100, (filled / 6) * 100)}%` }} /></div>
                    </button>
                  );
                })}
              </div>

              <div className="stage__section" style={{ marginTop: 40 }}>
                <Field label="Observações finais" hint="Algo que ficou de fora? Restrições, prazos internos, decisões pendentes, gente envolvida na aprovação." full>
                  <TextField multiline rows={5} value={state.obs} onChange={(x) => set("obs", x)} placeholder="Use este espaço como quiser." />
                </Field>
              </div>

              <div className="closing__actions">
                <button className="btn btn--solid btn--lg" onClick={submitToSheets} disabled={sending}>
                  {sending ? "Enviando..." : sent ? "Enviado! Reenviar" : "Enviar briefing para a Veddu"}
                </button>
                <button className="btn btn--ghost btn--lg" onClick={exportText}>Exportar .txt</button>
                <button className="btn btn--ghost btn--lg" onClick={() => window.print()}>Imprimir / PDF</button>
              </div>
              {sent && <p className="closing__sent">Briefing enviado em {new Date(getSentDate()).toLocaleString("pt-BR")}.</p>}
              <p className="closing__signoff">Obrigado. A Veddu Digital vai transformar isso em uma página que converte.</p>
              <ContactStrip variant="closing" />
            </section>
          )}
        </div>
      </div>

      {/* Sticky footer nav */}
      {!onCover && (
        <nav className="navbar">
          <div className="navbar__inner">
            <button className="btn btn--ghost" onClick={prev}>← Voltar</button>
            <div className="navbar__center">
              {!onReview && (
                <span className="navbar__progress">
                  <span className="navbar__progress-bar" style={{ width: `${(step / (totalSections + 1)) * 100}%` }} />
                </span>
              )}
            </div>
            {!onReview ? (
              <button className="btn btn--solid" onClick={next}>Próximo →</button>
            ) : (
              <button className="btn btn--solid" onClick={submitToSheets} disabled={sending}>
                {sending ? "Enviando..." : sent ? "Enviado!" : "Enviar →"}
              </button>
            )}
          </div>
        </nav>
      )}

      <TweaksPanelMount t={t} setTweak={setTweak} />
    </div>
  );
}

function TweaksPanelMount({ t, setTweak }) {
  return (
    <TweaksPanel title="Tweaks">
      <TweakSection title="Modo">
        <TweakRadio
          label="Layout"
          value={t.mode}
          options={[{ value: "guided", label: "Guiado" }, { value: "scroll", label: "Lista" }]}
          onChange={(v) => setTweak("mode", v)}
        />
      </TweakSection>
      <TweakSection title="Visual">
        <PalettePicker value={t.palette} onChange={(v) => setTweak("palette", v)} />
        <TweakSelect
          label="Fonte de título"
          value={t.headingFont}
          options={[
            { value: "Bricolage Grotesque", label: "Bricolage Grotesque" },
            { value: "Newsreader", label: "Newsreader" },
            { value: "Geist", label: "Geist" },
          ]}
          onChange={(v) => setTweak("headingFont", v)}
        />
        <TweakRadio
          label="Densidade"
          value={t.density}
          options={[{ value: "comfortable", label: "Confortável" }, { value: "compact", label: "Compacta" }]}
          onChange={(v) => setTweak("density", v)}
        />
        <TweakToggle label="Barra de etapas" value={t.showProgress} onChange={(v) => setTweak("showProgress", v)} />
      </TweakSection>
    </TweaksPanel>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<BriefingApp />);
