// dna-assessment.jsx — the Tier 4 gateway, built on the LIFE180 Funnel
// Architecture (entry · framing · exercise · results · insight · path).
// Scores across five DNA types + risk + current reality, then routes
// (Path A–D). Exports window.L180DNA. onRoute(result) hands the result up.

const DNA_STAGES = ["entry", "framing", "exercise", "results", "insight", "path"];
const DNA_STAGE_LABELS = ["Welcome", "The five types", "The assessment", "Your DNA", "What it means", "Your path"];

function L180DNA({ mode, onExit, onRoute }) {
  const Qs = window.L180_DNA_QUESTIONS;
  const hue = window.l180TierHue(4);
  const lsKey = "l180_dna";

  const [stage, setStage] = React.useState(0);
  const [qi, setQi] = React.useState(0);
  const [answers, setAnswers] = React.useState({});
  const [flags, setFlags] = React.useState({});
  const [openWhy, setOpenWhy] = React.useState(null);
  const [restored, setRestored] = React.useState(false);
  const advTimer = React.useRef(null);

  // save / resume
  React.useEffect(() => {
    try {
      const s = JSON.parse(localStorage.getItem(lsKey) || "null");
      if (s && s.answers) { setAnswers(s.answers); setStage(s.stage || 0); setQi(s.qi || 0); }
    } catch (e) {}
    setRestored(true);
  }, []);
  React.useEffect(() => {
    if (!restored) return;
    try { localStorage.setItem(lsKey, JSON.stringify({ answers, stage, qi })); } catch (e) {}
  }, [answers, stage, qi, restored]);

  const complete = Qs.every((q) => answers[q.id] != null);
  const result = React.useMemo(() => complete ? window.l180ScoreDNA(answers) : null, [complete, answers]);

  function choose(qid, idx) {
    setAnswers((a) => {
      const next = { ...a, [qid]: idx };
      const allDone = Qs.every((q) => next[q.id] != null);
      if (advTimer.current) clearTimeout(advTimer.current);
      advTimer.current = setTimeout(() => {
        if (allDone) setStage(3);
        else setQi((i) => Math.min(Qs.length - 1, i + 1));
      }, 220);
      return next;
    });
  }
  function reset() { setAnswers({}); setStage(0); setQi(0); try { localStorage.removeItem(lsKey); } catch (e) {} }

  const agentPrompts = {
    entry: "Frame this as the most important conversation in the process — everything routes from here.",
    framing: "Walk them through the five types in your words. Ask which they suspect they are before they answer.",
    exercise: "Let them answer on instinct. Flag any answer that contradicts what you know about them.",
    results: "Read the DNA and the blend out loud. Affirm the primary, note the secondary's influence.",
    insight: "This is the heart of it: DNA says who they're becoming, reality says what they need now. Hold both.",
    path: "Set expectations for where they're headed — the sub-pyramid or the lens — before you click through.",
  };

  // ---------- stage bodies ----------
  function Body() {
    // guard: result-stages need a computed result (never crash; just hold)
    if (stage >= 3 && !result) return null;
    switch (DNA_STAGES[stage]) {
      case "entry":
        return (
          <div className="l180-fstep" style={{ textAlign: "center", maxWidth: 640 }}>
            <div className="l180-eyebrow" style={{ color: hue }}>Tier 04 · The Routing Tier</div>
            <h2 className="l180-fbig">Discover Your Investor DNA</h2>
            <p className="l180-flead" style={{ margin: "0 auto 16px" }}>
              There is no universal “best” investment strategy — only what's aligned for <em>you</em>.
            </p>
            <p className="l180-fnote" style={{ maxWidth: 520, margin: "0 auto 22px" }}>
              This is the gateway. In about three minutes we'll find your primary DNA, your secondary blend, and where you actually live today — then route you to the path built for you.
            </p>
            <div className="l180-journey">
              {DNA_STAGE_LABELS.map((l, i) => (
                <div key={i} className="l180-journey-step">
                  <span className="l180-journey-dot" style={{ borderColor: hue }}>{i + 1}</span>
                  <span>{l}</span>
                </div>
              ))}
            </div>
            <div className="l180-timepill">About 3 minutes · {Qs.length} questions</div>
          </div>
        );

      case "framing":
        return (
          <div className="l180-fstep" style={{ maxWidth: 760 }}>
            <div className="l180-eyebrow" style={{ color: hue }}>The five types</div>
            <p className="l180-flead">
              Your <strong>DNA</strong> tells you who you're wired to become. Your <strong>current reality</strong> tells you what you need today. Strategy serves both.
            </p>
            <div className="l180-dnatypes">
              {Object.values(window.L180_DNA).map((d) => (
                <div key={d.key} className="l180-dnatype" style={{ borderColor: `color-mix(in oklch, ${d.color} 45%, transparent)` }}>
                  <span className="l180-dnatype-dot" style={{ background: d.color }} />
                  <div>
                    <strong style={{ color: d.color }}>{d.name}</strong>
                    <span className="l180-dnatype-dom">{d.domain}</span>
                    <p>{d.blurb}</p>
                  </div>
                </div>
              ))}
            </div>
          </div>
        );

      case "exercise": {
        const Q = Qs[qi];
        if (!Q) return null;
        const chosen = answers[Q.id];
        return (
          <div className="l180-fstep" style={{ maxWidth: 720 }}>
            <div className="l180-exrow">
              <div className="l180-eyebrow" style={{ color: hue }}>Question {qi + 1} / {Qs.length}</div>
              <button className="l180-whybtn" onClick={() => setOpenWhy(openWhy === Q.id ? null : Q.id)}>Why we ask</button>
            </div>
            {openWhy === Q.id && <div className="l180-whybox">{Q.why}</div>}
            <h2 className="l180-fbig" style={{ fontSize: 28, lineHeight: 1.22 }}>{Q.q}</h2>
            <div className="l180-dnaopts">
              {Q.opts.map((o, i) => (
                <button key={i} className={"l180-dnaopt" + (chosen === i ? " sel" : "")} style={{ "--hue": hue }}
                        onClick={() => choose(Q.id, i)}>
                  <span className="l180-dnaopt-dot" />
                  <span>{o.t}</span>
                </button>
              ))}
            </div>
            {mode === "agent" && (
              <button className={"l180-flagbtn" + (flags[Q.id] ? " on" : "")}
                      onClick={() => setFlags((f) => ({ ...f, [Q.id]: !f[Q.id] }))}>
                {flags[Q.id] ? "✓ Flagged for follow-up" : "⚑ Flag this answer"}
              </button>
            )}
          </div>
        );
      }

      case "results": {
        const primary = window.L180_DNA[result.primary];
        const secondary = window.L180_DNA[result.secondary];
        const maxScore = Math.max(...Object.values(result.scores)) || 1;
        return (
          <div className="l180-fstep" style={{ maxWidth: 720, textAlign: "center" }}>
            <div className="l180-eyebrow" style={{ color: primary.color }}>Your Investor DNA</div>
            <h2 className="l180-fbig" style={{ fontSize: 48, color: primary.color, margin: "6px 0 6px" }}>{primary.name}</h2>
            <p className="l180-flead" style={{ margin: "0 auto 4px", maxWidth: 520 }}>{primary.blurb}</p>
            <div className="l180-dnablend">with a <strong style={{ color: secondary.color }}>{secondary.name}</strong> secondary blend</div>
            <div className="l180-dnabars" style={{ maxWidth: 440, margin: "22px auto 6px" }}>
              {Object.keys(result.scores).sort((a, b) => result.scores[b] - result.scores[a]).map((k) => {
                const d = window.L180_DNA[k];
                return (
                  <div key={k} className="l180-dnabar">
                    <span className="l180-dnabar-name">{d.name}</span>
                    <div className="l180-dnabar-track">
                      <div className="l180-dnabar-fill" style={{ width: `${(result.scores[k] / maxScore) * 100}%`, background: d.color }} />
                    </div>
                  </div>
                );
              })}
            </div>
            <div className="l180-dnameta">
              <div className="l180-dnameta-item">
                <span>Risk profile</span>
                <strong style={{ color: L180_BRAND.risk[result.risk] }}>{result.riskLabel}</strong>
              </div>
              <div className="l180-dnameta-item">
                <span>Lives today</span>
                <strong style={{ color: window.L180_DNA[result.reality] ? window.L180_DNA[result.reality].color : "#fff" }}>
                  {window.L180_DNA[result.reality] ? window.L180_DNA[result.reality].name : "Getting started"}
                </strong>
              </div>
              <div className="l180-dnameta-item">
                <span>Path</span>
                <strong>Path {result.path}</strong>
              </div>
            </div>
          </div>
        );
      }

      case "insight": {
        const primary = window.L180_DNA[result.primary];
        return (
          <div className="l180-fstep" style={{ maxWidth: 640 }}>
            <div className="l180-eyebrow" style={{ color: primary.color }}>What your DNA means</div>
            <p className="l180-flead">{primary.meaning}</p>
            <div className="l180-implications">
              <div className="l180-impcard"><span style={{ color: primary.color }}>→</span> {result.pathNote}</div>
              <div className="l180-impcard"><span style={{ color: primary.color }}>★</span> <strong>The $50K Self-Investment Principle:</strong> before deploying capital, invest in becoming undeniably good at your path — mentorship, training, deal flow.</div>
            </div>
            <div className="l180-bridge" style={{ borderColor: `color-mix(in oklch, ${primary.color} 40%, transparent)` }}>
              <span className="l180-eyebrow" style={{ color: primary.color, fontSize: 9 }}>The principle</span>
              <p>“DNA tells you who you're becoming. Current reality tells you what you need today. We serve both.”</p>
            </div>
          </div>
        );
      }

      case "path": {
        const primary = window.L180_DNA[result.primary];
        const routesToSub = result.route === "analyst" || result.route === "strategist";
        const sub = routesToSub ? window.L180_SUBPYRAMIDS[result.route] : null;
        return (
          <div className="l180-fstep" style={{ maxWidth: 600, textAlign: "center" }}>
            <div className="l180-eyebrow" style={{ color: primary.color }}>Your path</div>
            <h2 className="l180-fbig">{routesToSub ? `Enter ${sub.name}` : "Stay on the main pyramid"}</h2>
            {routesToSub ? (
              <div className="l180-pathpreview" style={{ borderColor: `color-mix(in oklch, ${sub.theme} 45%, transparent)` }}>
                <div className="l180-pathpreview-top">{sub.dot} {sub.name} · {sub.domain}</div>
                <p className="l180-tagline-q" style={{ fontSize: 16, margin: "6px 0" }}>“{sub.tagline}”</p>
                <span className="l180-fnote">{sub.levels.length} levels · entry calibrated to your {result.riskLabel} risk profile.</span>
              </div>
            ) : (
              <p className="l180-flead" style={{ margin: "0 auto 18px", maxWidth: 480 }}>
                With a <strong style={{ color: primary.color }}>{primary.name}</strong> lens, you stay on the main pyramid with DNA-specific emphasis at Tiers 2, 3, and 5.
              </p>
            )}
            <button className="l180-bigcta" style={{ "--hue": routesToSub ? sub.theme : primary.color, marginTop: 16 }}
                    onClick={() => onRoute(result)}>
              {routesToSub ? `Enter ${sub.name} →` : "See my emphasis on the pyramid →"}
            </button>
          </div>
        );
      }
      default: return null;
    }
  }

  // ---------- nav ----------
  const inExercise = DNA_STAGES[stage] === "exercise";
  function back() {
    if (inExercise && qi > 0) { setQi((i) => i - 1); return; }
    setStage((s) => Math.max(0, s - 1));
  }
  function advance() { setStage((s) => Math.min(DNA_STAGES.length - 1, s + 1)); }
  const isResultLike = stage >= 3;

  return (
    <div className="l180-funnel" style={{ background: `radial-gradient(120% 85% at 50% -5%, #1c1c1e, ${L180_BRAND.navy} 58%, ${L180_BRAND.ink})` }}>
      <div className="l180-funnel-top">
        <button className="l180-back" onClick={onExit}>← {isResultLike ? "Back to pyramid" : "Exit assessment"}</button>
        <div className="l180-progress">
          {DNA_STAGES.map((_, i) => (
            <span key={i} className="l180-progdot" style={{ background: i <= stage ? hue : "rgba(255,255,255,.26)", width: i === stage ? 26 : 8 }} />
          ))}
        </div>
        {isResultLike
          ? <button className="l180-back" onClick={reset}>Retake ↺</button>
          : <div className="l180-stagelabel">{DNA_STAGE_LABELS[stage]}</div>}
      </div>

      <div className="l180-funnel-body">
        <div key={stage + "-" + qi} style={{ width: "100%", display: "flex", justifyContent: "center" }}>
          <Body />
        </div>
      </div>

      {mode === "agent" && (
        <div className="l180-funnel-agentbar">
          <div className="l180-agentpanel">
            <div className="l180-agentpanel-h">Agent · conversation prompt</div>
            <p>{agentPrompts[DNA_STAGES[stage]]}</p>
          </div>
        </div>
      )}

      <div className="l180-funnel-nav">
        {(stage > 0) ? <button className="l180-ghostbtn" onClick={back}>Back</button> : <span />}
        {inExercise
          ? <span className="l180-fnote" style={{ alignSelf: "center" }}>Pick the one that fits best</span>
          : DNA_STAGES[stage] === "path"
            ? <span />
            : <button className="l180-solidbtn" style={{ "--hue": hue }} onClick={advance}>
                {DNA_STAGES[stage] === "entry" ? "Begin assessment" : DNA_STAGES[stage] === "framing" ? "Start the questions" : DNA_STAGES[stage] === "results" ? "What this means" : "Continue"} →
              </button>}
      </div>
    </div>
  );
}

window.L180DNA = L180DNA;
