/* cst-tool-swot.jsx — "SWOT/Live": a strategist session that fills in a living
   decision board. Six dimensions, each ending in a NEXT DECISION.
   Layout variation: swotLayout = 'board' | 'compact'. Exported as SwotTool. */

const { useState: _wuS, useEffect: _wuE } = React;
const _WC = window.CST;
const _WD = window.CST_SWOT;
const { FONT: _wF, TEXT: _wT, HAZE: _wH, HAZE_DIM: _wHD, HAIR: _wHR, GLASS: _wG, STATUS: _wS } = _WC;

const STATUS_COLOR = { good: _wS.good, watch: _wS.watch, risk: _wS.risk };
const NODE_LABELS = ['Edge', 'Constraint', 'Window', 'Tempo', 'Capital', 'Pricing'];

function DimCard({ dim, data, accent, compact, onPriceIt }) {
  const sc = STATUS_COLOR[data.status];
  if (compact) {
    return (
      <div style={{ padding: '11px 0', borderBottom: `1px solid ${_wHR}` }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 6 }}>
          <span style={{ width: 18, height: 18, borderRadius: 5, background: sc + '22', color: sc, fontFamily: _wF, fontWeight: 800, fontSize: 11, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{dim.glyph}</span>
          <span style={{ flex: 1, fontFamily: _wF, fontWeight: 700, fontSize: 12.5, color: _wT, letterSpacing: -0.2 }}>{dim.label}</span>
          <span style={{ width: 7, height: 7, borderRadius: 99, background: sc, boxShadow: `0 0 8px ${sc}` }} />
        </div>
        <p style={{ margin: '0 0 6px', fontFamily: _wF, fontSize: 12, lineHeight: 1.45, color: 'rgba(236,237,241,0.82)' }}>{data.read}</p>
        <div style={{ display: 'flex', gap: 7, alignItems: 'baseline' }}>
          <span style={{ color: sc, fontSize: 11, flexShrink: 0 }}>→</span>
          <span style={{ fontFamily: _wF, fontSize: 11.5, lineHeight: 1.4, color: _wT, fontWeight: 600 }}>{data.decision}</span>
        </div>
        {dim.key === 'pricing' && <button onClick={onPriceIt} style={priceItBtn(_wS.good)}>Open Price-It →</button>}
      </div>);
  }
  return (
    <div style={{ borderRadius: 13, background: 'rgba(16,19,25,0.82)', border: `1px solid ${_wHR}`, borderLeft: `3px solid ${sc}`, padding: '13px 14px', backdropFilter: 'blur(10px)', WebkitBackdropFilter: 'blur(10px)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
        <span style={{ width: 26, height: 26, borderRadius: 7, background: sc + '1e', border: `1px solid ${sc}44`, color: sc, fontFamily: _wF, fontWeight: 800, fontSize: 14, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{dim.glyph}</span>
        <span style={{ flex: 1, fontFamily: _wF, fontWeight: 700, fontSize: 13.5, color: _wT, letterSpacing: -0.2, lineHeight: 1.1 }}>{dim.label}</span>
        <StatusChip label={_WD.STATUS_LABEL[data.status]} color={sc} />
      </div>
      <p style={{ margin: '0 0 11px', fontFamily: _wF, fontSize: 12.5, lineHeight: 1.5, color: 'rgba(236,237,241,0.82)' }}>{data.read}</p>
      <div style={{ borderTop: `1px dashed ${_wHR}`, paddingTop: 10 }}>
        <div style={{ fontFamily: _wF, fontSize: 9, letterSpacing: 2, color: sc, marginBottom: 5 }}>NEXT DECISION</div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'baseline' }}>
          <span style={{ color: sc, fontSize: 13, flexShrink: 0 }}>→</span>
          <span style={{ fontFamily: _wF, fontSize: 13, lineHeight: 1.45, color: _wT, fontWeight: 600 }}>{data.decision}</span>
        </div>
        {dim.key === 'pricing' && <button onClick={onPriceIt} style={priceItBtn(_wS.good)}>Open Price-It →</button>}
      </div>
    </div>);
}
function priceItBtn(c) {
  return { marginTop: 9, cursor: 'pointer', padding: '7px 11px', borderRadius: 9, fontFamily: _wF, fontWeight: 700, fontSize: 11, color: c, background: c + '16', border: `1px solid ${c}44` };
}

function SwotTool({ active, sim, accent, onExit, onBook, onOpenTool, swotLayout = 'board', onShare, decisionCtx, setDecisionCtx, decisionMeta }) {
  const c0 = accent[0];
  const [sub, setSub] = _wuS('session');         // session | analyze | board
  const [answers, setAnswers] = _wuS(null);
  const [board, setBoard] = _wuS(null);
  const [booked, setBooked] = _wuS(false);
  const [refreshing, setRefreshing] = _wuS(false);
  const [swotExamples, setSwotExamples] = _wuS({});   // tailored bottleneck chips
  const [exLoading, setExLoading] = _wuS({});
  const [ringDetail, setRingDetail] = _wuS(null);
  const run = useStrategistRun();

  const openRing = (score) => {
    const band = score >= 70 ? 'strong' : score >= 55 ? 'solid' : score >= 42 ? 'shaky' : 'weak';
    const text = { strong: 'You have what you need to act with confidence — move.', solid: 'Close — tighten the weak spots before you commit big.', shaky: 'Get clearer on the riskiest calls before you bet.', weak: 'Too many unknowns to act confidently yet — reduce them first.' }[band];
    setRingDetail({ label: 'Decision readiness', score, measures: 'How ready you are to act on these six decisions with confidence — your weakest dimensions drag it down.', read: { band, text } });
  };

  // after the business is described, fetch likely-bottleneck suggestions
  const tailorBottleneck = (i, ans) => {
    if (i !== 1 || swotExamples.bottleneck || exLoading.bottleneck) return;
    const ctx = ans && ans.ctx;
    if (!ctx || !ctx.trim()) return;
    setExLoading({ bottleneck: true });
    _WC.askAI(_WD.bottleneckExamplesPrompt(ctx)).then((raw) => {
      const opts = _WD.parseBottleneckExamples(raw);
      if (opts) setSwotExamples({ bottleneck: opts });
      setExLoading({});
    });
  };

  _wuE(() => { if (active && sim) { sim.seedAmbient(24); sim.setMode('ambient'); } }, [active]);

  // restore saved result from localStorage on mount
  _wuE(() => {
    if (!active) return;
    try {
      const saved = JSON.parse(localStorage.getItem('cst_result_swot'));
      if (saved && saved.board) {
        setAnswers(saved.answers || null); setBoard(saved.board); setSub('board');
      }
    } catch (e) {}
  }, [active]);

  const generate = (ans) => async () => {
    const raw = await _WC.askAI(_WD.boardPrompt(ans, decisionMeta));
    return (raw && _WD.parseBoard(raw)) || _WD.heuristicBoard(ans, decisionMeta);
  };

  const finish = (ans) => {
    setAnswers(ans); if (setDecisionCtx && ans.ctx) setDecisionCtx(ans.ctx); setSub('analyze'); setBoard(null); setBooked(false);
    run.start({ sim, lines: _WD.ANALYSIS_LINES, nodes: NODE_LABELS, build: generate(ans),
      onReady: (b) => { const bb = b || _WD.heuristicBoard(ans, decisionMeta); setBoard(bb); setSub('board'); window.CST_STATS.bumpRun('swot'); try { localStorage.setItem('cst_result_swot', JSON.stringify({ answers: ans, board: bb })); } catch (e) {} } });
  };

  // "refresh as inputs change" — re-run the read against the same answers
  const refresh = () => {
    if (!answers || refreshing) return;
    setRefreshing(true);
    if (sim) sim.run(() => {}, () => {});
    generate(answers)().then((b) => { setBoard(b || _WD.heuristicBoard(answers, decisionMeta)); setTimeout(() => setRefreshing(false), 500); });
  };

  const restart = () => { setAnswers(null); setBoard(null); setBooked(false); setSwotExamples({}); setExLoading({}); setSub('session'); try { localStorage.removeItem('cst_result_swot'); } catch (e) {} if (sim) { sim.seedAmbient(24); sim.setMode('ambient'); } };

  if (!active) return null;
  const compact = swotLayout === 'compact';

  return (
    <React.Fragment>
      {/* SESSION */}
      <StageCard active={sub === 'session'} dir="right" label="SWOT · session">
        <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none', background: 'linear-gradient(180deg, rgba(15,17,21,0.9) 0%, rgba(15,17,21,0.6) 30%, rgba(15,17,21,0.55) 60%, rgba(15,17,21,0.96) 100%)' }} />
        <div style={{ position: 'relative', height: '100%' }}>
          {sub === 'session' && (
            <ConversationFlow steps={_WD.STEPS} accent={accent} eyebrow="SWOT · session" advisorName="STRATEGIST"
              examplesFor={swotExamples} examplesLoading={exLoading} prefill={{ ctx: decisionCtx }}
              onStep={(i, ans) => { if (sim && i > 0) sim.run(() => {}, () => {}); tailorBottleneck(i, ans); }}
              onComplete={finish} />
          )}
        </div>
      </StageCard>

      {/* DECISION BOARD */}
      <StageCard active={sub === 'board'} dir="up" label="SWOT · board">
        <Scrim from={0.0} to={0.97} />
        {board && (() => { const spec = window.CST_SHARE.swotSpec(board, c0); return (
          <div style={{ position: 'relative', height: '100%', display: 'flex', flexDirection: 'column', padding: '0 20px 22px', gap: 12 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <Eyebrow color={c0}>SWOT · decision board</Eyebrow>
              <button onClick={refresh} style={{ display: 'flex', alignItems: 'center', gap: 5, background: _wG, border: `1px solid ${_wHR}`, borderRadius: 8, padding: '4px 8px', color: refreshing ? c0 : _wH, fontFamily: _wF, fontSize: 9.5, letterSpacing: 1, cursor: 'pointer' }}>
                <span style={{ display: 'inline-block', animation: refreshing ? 'cstSpin .7s linear infinite' : 'none' }}>↻</span>{refreshing ? 'UPDATING' : 'REFRESH'}
              </button>
            </div>

            <div style={{ display: 'flex', alignItems: 'center', gap: 13 }}>
              <div onClick={() => openRing(board.score)} style={{ cursor: 'pointer', position: 'relative' }}>
                <ScoreRing score={board.score} accent={c0} size={72} unit="READY" />
                <span style={{ position: 'absolute', right: -2, top: -2, width: 16, height: 16, borderRadius: 99, background: c0, color: _WC.INK, fontFamily: _wF, fontSize: 11, fontWeight: 800, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>?</span>
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, marginBottom: 5 }}>
                  <span style={{ width: 6, height: 6, borderRadius: 99, background: _wS.good, boxShadow: `0 0 8px ${_wS.good}`, animation: 'cstPulse 1.6s infinite' }} />
                  <span style={{ fontFamily: _wF, fontSize: 9.5, letterSpacing: 2, color: _wH }}>LIVE · UPDATES AS INPUTS CHANGE</span>
                </div>
                <div style={{ fontFamily: _wF, fontWeight: 700, fontSize: 14.5, color: _wT, letterSpacing: -0.3, lineHeight: 1.3 }}>{board.headline}</div>
              </div>
            </div>

            <IdentityBadge label={spec.badge} accent={c0} />
            <PeakShare accent={c0} label="Share your readiness" onShare={() => onShare && onShare(spec)} />
            <LeaderboardLine text={spec.leaderboard} accent={c0} />

            <div className="cst-scroll" style={{ flex: 1, minHeight: 0, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: compact ? 0 : 9, paddingRight: 2 }}>
              {_WD.DIMENSIONS.map((dim) => (
                <DimCard key={dim.key} dim={dim} data={board.dims[dim.key]} accent={accent} compact={compact}
                  onPriceIt={() => onOpenTool && onOpenTool('price')} />
              ))}
              <ReportUnlock accent={c0} tool="SWOT"
                resultHash={_WC.hashResult('swot:' + (answers && answers.ctx) + ':' + board.score)}
                includes={['Every dimension with its read + next decision', 'A status overview chart across all six', 'Your prioritised next three moves', 'A saved PDF you can share with your team']}
                sections={[{ title: 'Your next three moves', ordered: true, items: _WD.DIMENSIONS.map((d) => ({ d, x: board.dims[d.key] })).sort((a, b) => ({ good: 86, watch: 56, risk: 30 }[a.x.status] - { good: 86, watch: 56, risk: 30 }[b.x.status])).slice(0, 3).map(({ d, x }) => `${d.label}: ${x.decision}`) }]}
                buildSpec={() => window.CST_REPORT.swotReportSpec(answers, board, c0)}
                filename="cs-tech-swot-report" />
              <div style={{ height: 4 }} />
            </div>

            <HandoffRow currentId="swot" accent={c0} onGo={(id) => onOpenTool && onOpenTool(id)} />
            <ArtifactCTA accent={c0} tool="SWOT" onRestart={restart} restartLabel="Start a new read"
              onBook={onBook} />
            <FactorDetail factor={ringDetail} accent={c0} onClose={() => setRingDetail(null)} />
          </div>
        ); })()}
      </StageCard>

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

window.SwotTool = SwotTool;
