/* Briefing Hub Nexus — root app, flow config, tweaks */
(function () {
  const { useState, useMemo, useEffect } = React;
  const I = window.I;
  const N = window.NEXUS;
  const { Welcome, QuestionScreen, Computing } = window.SCREENS;
  const { Outcome } = window.OUTCOME;

  const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
    "direction": "precision",
    "accent": "#FFCD01",
    "density": "regular",
    "showProgress": true,
    "outcomeOverride": "auto",
    "welcomeTitle": "Vamos desenhar o seu próximo nível.",
    "welcomeHL": "próximo nível",
    "welcomeSub": "Algumas perguntas rápidas para entender seu momento. No final, você descobre o que sua empresa mais precisa agora — e o caminho para começar hoje.",
    "welcomeCta": "Começar briefing"
  }/*EDITMODE-END*/;

  const ACCENTS = {
    "#FFCD01": { ink: "#0A0A0A", hover: "#E6B800" },
    "#C8102E": { ink: "#FFFFFF", hover: "#E11D38" },
    "#34D399": { ink: "#06241A", hover: "#5BE0AC" },
    "#C9CCD3": { ink: "#0A0A0A", hover: "#DDE0E6" },
  };

  const DENSITY = { compact: 0.82, regular: 1, comfy: 1.16 };

  // ---------------- flow config ----------------
  const FLOW = [
    { id: "basics1", etapa: "Contato", type: "group",
      title: "Antes de tudo, quem é você?", hl: "quem é você",
      help: "É por aqui que enviamos seu diagnóstico e o acesso. Leva 20 segundos.",
      fields: [
        { id: "nome", label: "Nome", icon: "user", placeholder: "Seu nome", required: true, span: true },
        { id: "whatsapp", label: "WhatsApp", icon: "whats", pre: "+55", placeholder: "(00) 00000-0000", type: "tel", inputMode: "tel", required: true },
        { id: "email", label: "E-mail", icon: "mail", placeholder: "voce@empresa.com", type: "email", required: true },
      ] },
    { id: "basics2", etapa: "Contato", type: "group",
      title: "Agora, sobre a empresa.", hl: "empresa",
      fields: [
        { id: "empresa", label: "Empresa", icon: "building", placeholder: "Nome da empresa", required: true },
        { id: "cargo", label: "Cargo", placeholder: "Fundador, CMO, Sócio…" },
        { id: "cidade", label: "Cidade", icon: "pin", placeholder: "Cidade / UF" },
        { id: "site", label: "Site", placeholder: "empresa.com", optional: true },
        { id: "instagram", label: "Instagram", pre: "@", placeholder: "suaempresa", optional: true, span: true },
      ] },
    { id: "segment", etapa: "Sobre o negócio", type: "segment",
      title: "Qual o segmento da empresa?", options: N.SEGMENTS },
    { id: "revenue", etapa: "Sobre o negócio", type: "single",
      title: "Qual o faturamento mensal hoje?", hl: "faturamento mensal",
      help: "Sem julgamento — isso só nos ajuda a calibrar a solução certa para o seu porte.", options: N.REVENUE },
    { id: "team", etapa: "Sobre o negócio", type: "single",
      title: "Quantas pessoas no time?", options: N.TEAM },
    { id: "gargalo", etapa: "Diagnóstico", type: "single",
      title: "Onde sua operação trava hoje?", hl: "trava",
      help: "A resposta mais honesta é a que gera o melhor diagnóstico.", options: N.GARGALO },
    { id: "atendimento", etapa: "Diagnóstico", type: "single",
      title: "Como você atende quem chega?", hl: "atende", options: N.ATENDIMENTO },
    { id: "objective", etapa: "Diagnóstico", type: "single",
      title: "Qual seu principal objetivo agora?", hl: "principal objetivo", options: N.OBJECTIVE },
    { id: "difficulty", etapa: "Diagnóstico", type: "text", allowEmpty: true,
      title: "E qual sua maior dificuldade hoje?", hl: "maior dificuldade",
      help: "Escreva com suas palavras. É o que mais ajuda a gente a te entender.",
      placeholder: "Ex.: gero leads mas não consigo converter; não tenho processo de vendas…" },
    { id: "urgency", etapa: "Diagnóstico", type: "single",
      title: "Para quando você precisa de resultado?", hl: "quando", options: N.URGENCY },
    { id: "investsNow", etapa: "Marketing atual", type: "single",
      title: "Hoje você investe em marketing?", options: N.INVEST_NOW, cols: 2 },
    { id: "investAmount", etapa: "Marketing atual", type: "single",
      title: "Quanto investe por mês?", hl: "por mês", options: N.INVEST_AMOUNT,
      when: (a) => a.investsNow !== "Não" },
    { id: "channels", etapa: "Marketing atual", type: "multi", allowEmpty: true,
      title: "Quais canais você já usa?", help: "Pode marcar mais de um.", options: N.CHANNELS },
    { id: "solutions", etapa: "Soluções de interesse", type: "multi",
      title: "O que faz seus olhos brilharem?", hl: "olhos brilharem",
      help: "Selecione tudo que tem interesse. Isso calibra sua recomendação final.", options: N.SOLUTIONS },
  ];

  function emailOk(v) { return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v || ""); }

  const PRODUCT_OPTIONS = [{ value: "auto", label: "Automático (calculado)" }]
    .concat(Object.values(N.PRODUCTS).map((p) => ({ value: p.key, label: p.name })));

  function App() {
    const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
    const [phase, setPhase] = useState("welcome"); // welcome | flow | computing | outcome
    const [idx, setIdx] = useState(0);
    const [answers, setAnswers] = useState(() => {
      const pre = window.NXS_HANDOFF && window.NXS_HANDOFF.prefillFromUrl();
      return pre ? { basics1: pre } : {};
    });

    useEffect(() => {
      const boot = document.getElementById("boot");
      if (boot) { boot.classList.add("gone"); setTimeout(() => boot.remove(), 450); }
      window.__demo = (key) => { seedDemo(setAnswers); setTweak("outcomeOverride", key || "auto"); setPhase("outcome"); };
    }, []);

    const visible = useMemo(() => FLOW.filter((q) => !q.when || q.when(answers)), [answers]);
    const total = visible.length;
    const cur = visible[Math.min(idx, total - 1)];

    const acc = ACCENTS[t.accent] || ACCENTS["#FFCD01"];
    const rootStyle = {
      "--brand": t.accent,
      "--brand-hover": acc.hover,
      "--brand-ink": acc.ink,
      "--pad-scale": DENSITY[t.density] || 1,
    };

    const result = useMemo(() => N.scoreOf(answers), [answers]);
    const fit = useMemo(() => {
      const f = N.productFit(answers);
      if (t.outcomeOverride && t.outcomeOverride !== "auto") {
        const i = f.ranked.findIndex((p) => p.key === t.outcomeOverride);
        const topPct = f.ranked.length ? f.ranked[0].pct : 80;
        const forcedPct = Math.min(97, Math.max(topPct + 5, 62));
        if (i >= 0) { const [p] = f.ranked.splice(i, 1); f.ranked.unshift({ ...p, pct: Math.max(p.pct, forcedPct) }); }
        else { const P = N.PRODUCTS[t.outcomeOverride]; if (P) f.ranked.unshift({ ...P, pts: 99, pct: forcedPct }); }
      }
      return f;
    }, [answers, t.outcomeOverride]);

    const setAns = (id, v) => setAnswers((a) => ({ ...a, [id]: v }));
    const goNext = () => { if (idx >= total - 1) { setPhase("computing"); return; } setIdx((i) => i + 1); };    const goBack = () => { if (idx > 0) setIdx((i) => i - 1); };
    const restart = () => { setAnswers({}); setIdx(0); setPhase("welcome"); };

    let valid = true;
    if (cur) {
      if (cur.type === "group") {
        valid = cur.fields.every((f) => {
          if (!f.required) return true;
          const val = (answers[cur.id] || {})[f.id];
          if (f.type === "email") return emailOk(val);
          return val && val.trim().length > 1;
        });
      } else if (cur.type === "multi") {
        valid = cur.allowEmpty ? true : (answers[cur.id] || []).length > 0;
      }
    }

    const stepText = cur ? {
      num: String(visible.indexOf(cur) + 1).padStart(2, "0") + " / " + String(total).padStart(2, "0"),
      etapa: cur.etapa,
    } : null;

    const progress = phase === "welcome" ? 0 : phase === "flow" ? ((idx) / total) * 100 : 100;

    return (
      <div className={"bf-root dir-" + t.direction} style={rootStyle}>
        <div className="bf-bg" aria-hidden="true">
          <div className="grid" />
          <div className="glow" />
          <div className="vignette" />
        </div>

        <header className="bf-top">
          <div className="bf-brand">
            <img className="orb" src={(window.__resources && window.__resources.orb) || "assets/brand/bolinha.png"} alt="" />
            <div>
              <div className="wm">NEXUS</div>
              <div className="sub">Briefing Hub</div>
            </div>
          </div>
          <span className="spacer" />
          <span className="bf-secure"><span className="dotk" /> Conexão segura · dados protegidos</span>
        </header>

        {t.showProgress && phase !== "welcome" && (
          <div className="bf-progress-wrap">
            <div className="bf-progress"><i style={{ width: progress + "%" }} /></div>
            <div className="bf-progress-meta">
              <span>{phase === "flow" && cur ? cur.etapa : phase === "computing" ? "Analisando" : "Diagnóstico"}</span>
              <span className="mono">{Math.round(progress)}%</span>
            </div>
          </div>
        )}

        <main className="bf-stage">
          <div className="bf-panel">
            {phase === "welcome" && <Welcome t={t} onStart={() => { setPhase("flow"); setIdx(0); }} />}
            {phase === "flow" && cur && (
              <QuestionScreen key={cur.id}
                q={{ ...cur, valid, allowEmpty: cur.allowEmpty }}
                value={answers[cur.id]}
                onChange={(v) => setAns(cur.id, v)}
                onNext={goNext} onBack={goBack} canBack={idx > 0}
                stepText={stepText} t={t} />
            )}
            {phase === "computing" && (
              <Computing score={result.score} t={t} onDone={() => {
                setPhase("outcome");
                const H = window.NXS_HANDOFF;
                if (H) {
                  const basics = { ...(answers.basics1 || {}), ...(answers.basics2 || {}) };
                  H.trackLead(basics);
                  H.sendToHelena({
                    lead: basics, respostas: answers,
                    recomendacao: fit.ranked.slice(0, 3).map((p) => ({ produto: p.name, key: p.key, fit: p.pct })),
                    lead_score: result.score, prioridade: N.TIERS[result.tier].label,
                  });
                }
              }} />
            )}
            {phase === "outcome" && (
              <Outcome fit={fit} score={result.score} tier={result.tier} answers={answers}
                lines={result.lines} t={t} onRestart={restart} />
            )}
          </div>
        </main>

        <TweaksPanel>
          <TweakSection label="Direção visual" />
          <TweakRadio label="Estilo" value={t.direction}
            options={["precision", "cinematic", "editorial"]}
            onChange={(v) => setTweak("direction", v)} />
          <TweakColor label="Cor de acento" value={t.accent}
            options={Object.keys(ACCENTS)}
            onChange={(v) => setTweak("accent", v)} />
          <TweakRadio label="Densidade" value={t.density}
            options={["compact", "regular", "comfy"]}
            onChange={(v) => setTweak("density", v)} />
          <TweakToggle label="Barra de progresso" value={t.showProgress}
            onChange={(v) => setTweak("showProgress", v)} />

          <TweakSection label="Demonstração do diagnóstico" />
          <TweakSelect label="Forçar produto recomendado" value={t.outcomeOverride}
            options={PRODUCT_OPTIONS}
            onChange={(v) => setTweak("outcomeOverride", v)} />
          <TweakButton label="Ir direto ao resultado"
            onClick={() => { if (Object.keys(answers).length === 0) seedDemo(setAnswers); setPhase("outcome"); }} />

          <TweakSection label="Texto — boas-vindas" />
          <TweakText label="Título" value={t.welcomeTitle}
            onChange={(v) => setTweak("welcomeTitle", v)} />
          <TweakText label="Palavra em destaque" value={t.welcomeHL}
            onChange={(v) => setTweak("welcomeHL", v)} />
          <TweakText label="Subtítulo" value={t.welcomeSub}
            onChange={(v) => setTweak("welcomeSub", v)} />
          <TweakText label="Botão" value={t.welcomeCta}
            onChange={(v) => setTweak("welcomeCta", v)} />
        </TweaksPanel>
      </div>
    );
  }

  function seedDemo(setAnswers) {
    setAnswers({
      basics1: { nome: "Marina Alves", whatsapp: "(11) 98888-0000", email: "marina@vertice.com" },
      basics2: { empresa: "Studio Vértice", cargo: "Fundadora", cidade: "São Paulo / SP" },
      segment: "Serviços",
      revenue: "R$100 mil a R$300 mil",
      team: "6 a 15",
      gargalo: "Vendo, mas o atendimento é bagunçado",
      atendimento: "Planilhas e anotações",
      objective: "Escalar operação",
      difficulty: "Geramos leads mas falta processo de vendas e automação.",
      urgency: "Nos próximos 30 dias",
      investsNow: "Sim",
      investAmount: "R$3.000 a R$10.000",
      channels: ["Instagram", "Google Ads"],
      solutions: ["Growth Marketing", "CRM", "Automação", "WhatsApp API", "Tráfego Pago", "Consultoria Estratégica"],
    });
  }

  window.BriefingApp = App;
})();
