/* cst-tool-validate.jsx — "Validate an idea" (the Proving Ground flow), refactored
   into a hub-routable tool. idea → focus → analyze → verdict artifact → CTA.
   Exported to window as ValidateTool. */

const { useState: _vuS, useEffect: _vuE } = React;
const _VC = window.CST;
const _VD = window.CST_VALIDATE;
const { FONT: _vF, TEXT: _vT, HAZE: _vH, HAZE_DIM: _vHD, HAIR: _vHR, GLASS: _vG } = _VC;

function ValidateTool({ active, sim, accent, onExit, onBook, onShare, onOpenTool, decisionCtx, setDecisionCtx, setDecisionMeta }) {
  const c0 = accent[0];
  const [sub, setSub] = _vuS('idea'); // idea | focus | analyze | verdict
  const [idea, setIdea] = _vuS('');
  const [focus, setFocus] = _vuS(null);
  const [focusOpts, setFocusOpts] = _vuS(null); // idea-specific options (null = use generic)
  const [focusLoading, setFocusLoading] = _vuS(false);
  const [verdict, setVerdict] = _vuS(null);
  const [booked, setBooked] = _vuS(false);
  const [selFactor, setSelFactor] = _vuS(null); // tapped radar point
  const [prompt] = _vuS(() => _VD.IDEA_PROMPTS[Math.floor(Math.random() * _VD.IDEA_PROMPTS.length)]);
  const [autoAdvance, setAutoAdvance] = _vuS(false); // flag to auto-advance after idea set
  const run = useStrategistRun();

  // entering the tool: ambient field
  _vuE(() => {if (active && sim) {sim.seedAmbient(26);sim.setMode('ambient');}}, [active]);

  // On tool open: restore saved result, OR prefill + flag auto-advance
  _vuE(() => {
    if (!active || sub !== 'idea') return;
    // try restoring a previous result first
    try {
      const saved = JSON.parse(localStorage.getItem('cst_result_validate'));
      if (saved && saved.verdict) {
        setIdea(saved.idea || ''); setFocus(saved.focus || null); setVerdict(saved.verdict); setSub('verdict');
        return;
      }
    } catch (e) {}
    // prefill from shared context + flag auto-advance for next render
    if (!idea && decisionCtx && decisionCtx.trim()) {
      setIdea(decisionCtx);
      setAutoAdvance(true);
    }
  }, [active]);

  // auto-advance to focus step once idea is set from context
  _vuE(() => {
    if (autoAdvance && idea.trim() && sub === 'idea') {
      setAutoAdvance(false);
      goFocus();
    }
  }, [autoAdvance, idea]);

  const generate = async () => {
    const raw = await _VC.askAI(_VD.verdictPrompt(idea, focus));
    return raw && _VD.parseVerdict(raw) || _VD.heuristicVerdict(idea, focus);
  };

  // idea → focus: generate options tailored to the idea (generic fallback)
  const goFocus = async () => {
    if (!idea.trim()) return;
    if (setDecisionCtx) setDecisionCtx(idea);
    setSub('focus');setFocusOpts(null);setFocusLoading(true);
    let opts = _VD.parseFocusOptions(await _VC.askAI(_VD.focusOptionsPrompt(idea)));
    if (!opts) opts = _VD.parseFocusOptions(await _VC.askAI(_VD.focusOptionsPrompt(idea))); // one retry before fallback
    setFocusOpts(opts || _VD.FOCUS);
    setFocusLoading(false);
  };

  const pickFactor = (d) => {
    const meta = _VD.BREAKDOWN_FACTORS.find((f) => f.key === d.key) || {};
    setSelFactor({ label: d.label, score: d.value, measures: meta.measures, read: _VD.factorRead(d.key, d.value) });
  };

  const begin = (f) => {
    setFocus(f);setSub('analyze');setVerdict(null);setBooked(false);
    run.start({
      sim, lines: _VD.ANALYSIS_LINES, nodes: _VD.EXPLORE_NODES,
      build: generate, onReady: (v) => {const vv = v || _VD.heuristicVerdict(idea, f);setVerdict(vv);setSub('verdict');window.CST_STATS.bumpRun('validate');if (setDecisionMeta) setDecisionMeta({ edge: f.label, edgeKey: f.key, ideaScore: vv.score, from: 'validate' });try { localStorage.setItem('cst_result_validate', JSON.stringify({ idea, focus: f, verdict: vv })); } catch (e) {}}
    });
  };

  const restart = () => {setIdea('');setFocus(null);setFocusOpts(null);setFocusLoading(false);setVerdict(null);setBooked(false);setSelFactor(null);setSub('idea');try { localStorage.removeItem('cst_result_validate'); } catch (e) {}if (sim) {sim.seedAmbient(26);sim.setMode('ambient');}};

  if (!active) return null;
  const band = verdict ? _VD.scoreBand(verdict.score) : null;
  const peek = verdict ? verdict.market : '';
  const spec = verdict ? window.CST_SHARE.ideaSpec(verdict, idea, c0) : null;

  return (
    <React.Fragment>
      {/* IDEA */}
      <StageCard active={sub === 'idea'} dir="right" label="Validate · idea">
        <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none', background: 'linear-gradient(180deg, rgba(15,17,21,0.93) 0%, rgba(15,17,21,0.62) 28%, rgba(15,17,21,0.5) 54%, rgba(15,17,21,0.62) 78%, rgba(15,17,21,0.97) 100%)' }} />
        <div style={{ position: 'relative', height: '100%', display: 'flex', flexDirection: 'column', padding: '6px 22px 26px', gap: 11 }}>
          <Eyebrow color={c0}>Validate · your idea</Eyebrow>
          <h2 style={{ margin: 0, fontFamily: _vF, fontWeight: 700, fontSize: 25, letterSpacing: -1, lineHeight: 1.15, color: _vT }}>{prompt}</h2>
          <textarea className="cst-idea-input" value={idea} autoFocus onChange={(e) => setIdea(e.target.value)} placeholder="Start typing your idea…"
          style={{ flex: 1, minHeight: 0, width: '100%', boxSizing: 'border-box', resize: 'none', userSelect: 'text', background: 'transparent', border: 'none', outline: 'none', overflowY: 'auto', color: _vT, fontFamily: _vF, fontWeight: 700, fontSize: 21, lineHeight: 1.32, letterSpacing: -0.3, padding: '2px 0', marginTop: 2 }} />
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7, alignItems: 'center' }}>
            <span style={{ fontFamily: _vF, fontSize: 10.5, color: _vH, letterSpacing: 1 }}>TRY:</span>
            {_VD.EXAMPLE_IDEAS.map((ex) =>
            <button key={ex} onClick={() => setIdea(ex)} style={{ cursor: 'pointer', padding: '6px 10px', borderRadius: 9, fontFamily: _vF, fontSize: 11, color: _vH, background: _vG, border: `1px solid ${_vHR}` }}>{ex.length > 30 ? ex.slice(0, 28) + '…' : ex}</button>
            )}
          </div>
          <PrimaryBtn accent={c0} disabled={!idea.trim()} onClick={goFocus}>{idea.trim() ? 'Continue →' : 'Describe your idea to continue'}</PrimaryBtn>
        </div>
      </StageCard>

      {/* FOCUS */}
      <StageCard active={sub === 'focus'} dir="right" label="Validate · focus">
        <div style={{ position: 'relative', height: '100%', display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', padding: '0 22px 26px', gap: 12 }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            <Eyebrow color={c0}>Validate · what makes it special</Eyebrow>
            <h2 style={{ margin: 0, fontFamily: _vF, fontWeight: 700, fontSize: 22, letterSpacing: -0.5, color: _vT }}>What makes your idea stand out?</h2>
            <p style={{ margin: 0, fontFamily: _vF, fontSize: 12, color: _vH, lineHeight: 1.4 }}>Pick what makes “{idea.trim().length > 38 ? idea.trim().slice(0, 36) + '…' : idea.trim()}” different.</p>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {focusLoading && (!focusOpts || focusOpts === _VD.FOCUS) ?

            <React.Fragment>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '2px 2px 6px' }}>
                    <TypingDots color={c0} />
                    <span style={{ fontFamily: _vF, fontSize: 12, color: _vH }}>Reading your idea…</span>
                  </div>
                  {[0, 1, 2, 3].map((i) =>
              <div key={i} style={{ height: 58, borderRadius: 13, background: 'rgba(236,237,241,0.05)', border: `1px solid ${_vHR}`, opacity: 1 - i * 0.16, animation: 'cstPulse 1.4s infinite' }} />
              )}
                </React.Fragment> :

            (focusOpts || _VD.FOCUS).map((f, i) => <ChoiceCard key={f.key + i} label={f.label} sub={f.desc} accent={accent[i % accent.length]} onPick={() => begin(f)} />)}
          </div>
        </div>
      </StageCard>

      {/* VERDICT */}
      <StageCard active={sub === 'verdict'} dir="up" label="Validate · verdict">
        <Scrim from={0.0} to={0.97} />
        {verdict &&
        <div style={{ position: 'relative', height: '100%', display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', padding: '0 24px 24px', gap: 14 }}>
            <Eyebrow color={c0}>Validate · your read</Eyebrow>
            <div className="cst-scroll" style={{ overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 12 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 15 }}>
                <ScoreRing score={verdict.score} accent={c0} size={98} />
                <div style={{ flex: 1 }}>
                  <IdentityBadge label={spec.badge} accent={c0} style={{ marginBottom: 7 }} />
                  <div style={{ fontFamily: _vF, fontWeight: 700, fontSize: 17, color: _vT, letterSpacing: -0.3, lineHeight: 1.2 }}>{verdict.verdict}</div>
                  <p style={{ margin: '6px 0 0', fontFamily: _vF, fontSize: 12, lineHeight: 1.45, color: _vH }}>{verdict.summary}</p>
                </div>
              </div>
              <PeakShare accent={c0} label="Share your score" onShare={() => onShare && onShare(spec)} />
              <LeaderboardLine text={spec.leaderboard} accent={c0} />
              <div style={{ fontFamily: _vF, fontSize: 10.5, letterSpacing: 1.5, color: c0 }}>HOW IT SCORES · TAP A POINT</div>
              <div style={{ display: 'flex', justifyContent: 'center', marginTop: -4 }}><RadarChart factors={_VD.BREAKDOWN_FACTORS} breakdown={verdict.breakdown} accent={c0} onPick={pickFactor} /></div>
              <div style={{ borderTop: `1px solid ${_vHR}`, paddingTop: 11 }}>
                <div style={{ fontFamily: _vF, fontSize: 10.5, letterSpacing: 1, color: c0, marginBottom: 5 }}>WHO TO TRY IT WITH FIRST</div>
                <p style={{ margin: 0, fontFamily: _vF, fontSize: 12.5, lineHeight: 1.5, color: 'rgba(236,237,241,0.82)' }}>{peek}</p>
              </div>

              {/* full report — 99¢ one-time, multi-page PDF */}
              <ReportUnlock accent={c0} tool="Idea check" includes={_VD.REPORT_INCLUDES}
                resultHash={_VC.hashResult('validate:' + idea + ':' + (focus && focus.key))}
                sections={[
                  { title: 'What to watch', items: verdict.risks || [], ordered: true },
                  { title: 'Your first steps', items: verdict.nextSteps || [], ordered: true },
                ]}
                buildSpec={() => window.CST_REPORT.validateReportSpec(idea, focus, verdict, c0)}
                filename="cs-tech-idea-report" />
            </div>
            <HandoffRow currentId="validate" accent={c0} onGo={(id) => onOpenTool && onOpenTool(id)} />
            <ArtifactCTA accent={c0} tool="Idea check" onRestart={restart} restartLabel="Validate another idea"
          onBook={onBook} />
            <FactorDetail factor={selFactor} accent={c0} onClose={() => setSelFactor(null)} />
          </div>
        }
      </StageCard>

      {run.analyzing && <AnalyzeOverlay lines={_VD.ANALYSIS_LINES} idx={run.statusIdx} accent={c0} count={run.count} countNoun="things checked" />}
    </React.Fragment>);
}

window.ValidateTool = ValidateTool;