/* Briefing Hub Nexus — Welcome, Question renderer, Computing → window.SCREENS */
(function () {
  const { useState, useEffect, useRef } = React;
  const I = window.I;
  const { Ring, useCountUp } = window.UI;

  const KEYS = "ABCDEFGHIJ".split("");

  function renderTitle(title, hl) {
    if (!hl || !title.includes(hl)) return title;
    const parts = title.split(hl);
    return (
      <>
        {parts[0]}
        <span className="hl">{hl}</span>
        {parts.slice(1).join(hl)}
      </>
    );
  }

  /* ---------------------------------------------------- WELCOME */
  function Welcome({ t, onStart }) {
    return (
      <div className="bf-screen bf-welcome">
        <div className="bf-mark">
          <div className="bf-ring r2" />
          <div className="bf-ring r1" />
          <div className="bf-ring r3" />
          <img src={(window.__resources && window.__resources.xgold) || "assets/brand/x-gold.png"} alt="Nexus" />
        </div>
        <h1>{renderTitle(t.welcomeTitle, t.welcomeHL)}</h1>
        <p className="lede">{t.welcomeSub}</p>
        <div className="bf-meta-row">
          <span className="it"><I.clock size={16} /> 2 minutos</span>
          <span className="it"><I.spark size={16} /> Resposta inteligente</span>
          <span className="it"><I.target size={16} /> Plano de ação na hora</span>
        </div>
        <button className="bf-cta" onClick={onStart}>
          {t.welcomeCta} <I.arrowR size={18} />
        </button>
        <p className="bf-trust">Construímos sistemas. Não vendemos planilhas.</p>
      </div>
    );
  }

  /* ---------------------------------------------------- QUESTION */
  function QuestionScreen({ q, value, onChange, onNext, onBack, canBack, stepText, t }) {
    const advTimer = useRef(0);
    useEffect(() => () => clearTimeout(advTimer.current), []);

    const pickSingle = (v) => {
      onChange(v);
      clearTimeout(advTimer.current);
      advTimer.current = setTimeout(onNext, 260);
    };

    // keyboard select for single/segment
    useEffect(() => {
      if (q.type !== "single" && q.type !== "segment") return;
      const h = (e) => {
        const opts = q.options.map((o) => o.v ?? o);
        const idx = KEYS.indexOf(e.key.toUpperCase());
        if (idx >= 0 && idx < opts.length) pickSingle(opts[idx]);
        if (e.key === "Enter" && value) onNext();
      };
      window.addEventListener("keydown", h);
      return () => window.removeEventListener("keydown", h);
    }, [q, value]);

    let body = null;
    if (q.type === "single" || q.type === "segment") {
      body = (
        <div className={"bf-opts" + (q.cols === 2 || q.type === "segment" ? " cols-2" : "")}>
          {q.options.map((o, i) => {
            const v = o.v ?? o;
            const sel = value === v;
            return (
              <button key={v} className={"bf-opt" + (sel ? " is-sel" : "")} onClick={() => pickSingle(v)}>
                <span className="key">{sel ? <I.check size={13} /> : KEYS[i]}</span>
                <span className="lab">{v}</span>
                <span className="tick"><I.arrowR size={16} /></span>
              </button>
            );
          })}
        </div>
      );
    } else if (q.type === "multi") {
      const arr = value || [];
      const toggle = (v) => {
        if (arr.includes(v)) onChange(arr.filter((x) => x !== v));
        else onChange([...arr, v]);
      };
      body = (
        <div className="bf-multi">
          {q.options.map((o) => {
            const v = o.v ?? o;
            const sel = arr.includes(v);
            return (
              <button key={v} className={"bf-mchip" + (sel ? " is-sel" : "")} onClick={() => toggle(v)}>
                <span className="box">{sel && <I.check size={11} />}</span>
                {v}
              </button>
            );
          })}
        </div>
      );
    } else if (q.type === "text") {
      body = (
        <div className="bf-fields">
          <div className="bf-field">
            <div className="bf-inwrap">
              <textarea rows={3} autoFocus placeholder={q.placeholder}
                value={value || ""} onChange={(e) => onChange(e.target.value)} />
            </div>
          </div>
        </div>
      );
    } else if (q.type === "group") {
      const vals = value || {};
      const setF = (id, v) => onChange({ ...vals, [id]: v });
      body = (
        <div className="bf-fields two">
          {q.fields.map((f) => {
            const Ico = f.icon ? I[f.icon] : null;
            const invalid = f._invalid;
            return (
              <div key={f.id} className={"bf-field" + (f.span ? " col-span" : "") + (invalid ? " invalid" : "")}>
                <label>{f.label}{f.optional && <span className="opt">opcional</span>}</label>
                <div className="bf-inwrap">
                  {Ico && <Ico size={16} style={{ color: "var(--text-subtle)", flexShrink: 0 }} />}
                  {f.pre && <span className="pre">{f.pre}</span>}
                  <input type={f.type || "text"} placeholder={f.placeholder} inputMode={f.inputMode}
                    value={vals[f.id] || ""} onChange={(e) => setF(f.id, e.target.value)} />
                </div>
              </div>
            );
          })}
        </div>
      );
    }

    const multiCount = q.type === "multi" ? (value || []).length : 0;

    return (
      <div className="bf-screen">
        <div className="bf-qhead">
          <div className="bf-step">
            <span className="num">{stepText.num}</span>
            <span className="et">{stepText.etapa}</span>
          </div>
          <h2 className="bf-qtitle">{renderTitle(q.title, q.hl)}</h2>
          {q.help && <p className="bf-qhelp">{q.help}</p>}
        </div>
        {body}
        <div className="bf-nav">
          {canBack && <button className="bf-back" onClick={onBack}><I.arrowL size={16} /> Voltar</button>}
          <span className="spacer" />
          {(q.type === "multi" || q.type === "group" || q.type === "text") ? (
            <>
              {q.type === "multi" && (
                <span className="bf-hint" style={{ marginRight: 4 }}>
                  {multiCount > 0 ? `${multiCount} selecionada${multiCount > 1 ? "s" : ""}` : "Selecione tudo que se aplica"}
                </span>
              )}
              <button className="bf-cta" onClick={onNext} disabled={!q.allowEmpty && !q.valid}>
                Continuar <I.arrowR size={18} />
              </button>
            </>
          ) : (
            <span className="bf-hint">Pressione <span className="kbd">A–{KEYS[q.options.length - 1]}</span> ou toque</span>
          )}
        </div>
      </div>
    );
  }

  /* ---------------------------------------------------- COMPUTING */
  function Computing({ score, onDone, t }) {
    const STEPS = [
      "Analisando perfil e momento do negócio",
      "Localizando o gargalo principal",
      "Cruzando com as soluções do ecossistema",
      "Montando seu plano de ação",
    ];
    const [phase, setPhase] = useState(0);
    const [showScore, setShowScore] = useState(false);
    const n = useCountUp(showScore ? score : 0, 800, true);

    useEffect(() => {
      const timers = [];
      STEPS.forEach((_, i) => timers.push(setTimeout(() => setPhase(i + 1), 380 + i * 540)));
      timers.push(setTimeout(() => setShowScore(true), 380 + STEPS.length * 540));
      timers.push(setTimeout(onDone, 380 + STEPS.length * 540 + 1250));
      return () => timers.forEach(clearTimeout);
    }, []);

    return (
      <div className="bf-screen bf-computing">
        <div className="bf-meter">
          <Ring size={168} stroke={9} value={showScore ? score : (phase / STEPS.length) * 70} color="var(--brand)">
            <span className="val">{showScore ? n : ""}</span>
            {!showScore && <I.spark size={30} style={{ color: "var(--brand)" }} />}
          </Ring>
        </div>
        <h2>{showScore ? "Diagnóstico pronto." : "Lendo seu briefing…"}</h2>
        <div className="steps">
          {STEPS.map((s, i) => (
            <span key={i} className={"bf-cstep" + (phase > i ? " on" : "")}>
              <span className="ck">{phase > i ? <I.check size={11} /> : ""}</span>{s}
            </span>
          ))}
        </div>
      </div>
    );
  }

  window.SCREENS = { Welcome, QuestionScreen, Computing };
})();
