/* cst-tool-price.jsx — "Price-It": Mode A price a job, Mode B value a business.
   The numbers are computed locally and shown plainly; the takeaway is AI-written.
   Layout variation: priceLayout = 'bars' | 'cards'. Exported as PriceTool. */

const { useState: _puS, useEffect: _puE } = React;
const _PC = window.CST;
const _PD = window.CST_PRICE;
const { FONT: _pF, TEXT: _pT, HAZE: _pH, HAZE_DIM: _pHD, HAIR: _pHR, GLASS: _pG, STATUS: _pS } = _PC;

const FLAG_COLOR = { losing: _pS.risk, under: _pS.watch, ok: _pS.good, none: _pH };

// a labelled horizontal bar (the "visible math")
function BarRow({ label, value, max, color, valueText, emphasis, info, onInfo }) {
  const pct = max > 0 ? Math.max(2, Math.min(100, value / max * 100)) : 2;
  const tappable = info && onInfo;
  return (
    <div onClick={tappable ? () => onInfo({ title: label, value: valueText, body: info }) : undefined}
    style={{ display: 'flex', flexDirection: 'column', gap: 4, cursor: tappable ? 'pointer' : 'default' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <span style={{ fontFamily: _pF, fontSize: 10.5, color: emphasis ? _pT : _pH, fontWeight: emphasis ? 700 : 500, letterSpacing: 0.2 }}>{label}{tappable && <span style={{ color: _pHD, marginLeft: 5 }}>ⓘ</span>}</span>
        <span style={{ fontFamily: _pF, fontSize: emphasis ? 13 : 11.5, color: emphasis ? color : _pH, fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>{valueText}</span>
      </div>
      <div style={{ height: emphasis ? 9 : 6, borderRadius: 99, background: 'rgba(236,237,241,0.08)', overflow: 'hidden' }}>
        <div style={{ width: pct + '%', height: '100%', borderRadius: 99, background: color, boxShadow: emphasis ? `0 0 12px ${color}` : 'none', transition: 'width .9s cubic-bezier(.2,.8,.2,1)' }} />
      </div>
    </div>);
}

function StatCard({ label, value, sub, color }) {
  return (
    <div style={{ background: _pG, border: `1px solid ${_pHR}`, borderRadius: 11, padding: '11px 12px' }}>
      <div style={{ fontFamily: _pF, fontSize: 9.5, letterSpacing: 1, color: _pHD, textTransform: 'uppercase', marginBottom: 5 }}>{label}</div>
      <div style={{ fontFamily: _pF, fontSize: 19, fontWeight: 800, color: color || _pT, letterSpacing: -0.5, lineHeight: 1 }}>{value}</div>
      {sub && <div style={{ fontFamily: _pF, fontSize: 10, color: _pH, marginTop: 4, lineHeight: 1.3 }}>{sub}</div>}
    </div>);
}

function Takeaway({ take, accent }) {
  if (!take) return null;
  return (
    <div style={{ borderTop: `1px solid ${_pHR}`, paddingTop: 11 }}>
      <div style={{ fontFamily: _pF, fontSize: 9.5, letterSpacing: 2, color: accent, marginBottom: 6 }}>THE BLUNT TRUTH</div>
      <p style={{ margin: '0 0 9px', fontFamily: _pF, fontSize: 13, lineHeight: 1.5, color: _pT, fontWeight: 600 }}>{take.verdict}</p>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {take.levers.map((l, i) =>
        <div key={i} style={{ display: 'flex', gap: 8, alignItems: 'baseline' }}>
            <span style={{ color: accent, fontSize: 11, flexShrink: 0 }}>→</span>
            <span style={{ fontFamily: _pF, fontSize: 12, lineHeight: 1.4, color: _pH }}>{l}</span>
          </div>
        )}
      </div>
    </div>);
}

// ----- Mode A: priced job -----
function JobResult({ r, accent, layout, spec, onShare, onInfo }) {
  const flag = FLAG_COLOR[r.flag];
  const isHour = r.basis === 'hour';
  const max = Math.max(r.scenarioPrice, r.price, r.costPerUnit, 1) * 1.1;
  const perU = isHour ? '/hr' : ` / ${r.unitLabel}`;
  return (
    <div className="cst-scroll" style={{ flex: 1, minHeight: 0, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 14, paddingRight: 2 }}>
      <div>
        <div style={{ fontFamily: _pF, fontSize: 10, letterSpacing: 1.5, color: _pHD, marginBottom: 4 }}>YOUR TIME IS REALLY EARNING</div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
          <span style={{ fontFamily: _pF, fontWeight: 800, fontSize: 44, color: flag, letterSpacing: -2, lineHeight: 1 }}>{_PC.moneyFull(r.effHourly)}</span>
          <span style={{ fontFamily: _pF, fontSize: 15, color: _pH, fontWeight: 600 }}>/ hr</span>
        </div>
        <p style={{ margin: '8px 0 0', fontFamily: _pF, fontSize: 13, lineHeight: 1.45, color: _pT, fontWeight: 600 }}>{r.headline}</p>
      </div>

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

      {/* visible math, normalised to a month so any business can read it */}
      <div style={{ background: _pG, border: `1px solid ${_pHR}`, borderRadius: 10, padding: '10px 12px', fontFamily: _pF, fontSize: 11.5, color: _pH, lineHeight: 1.7 }}>
        <span style={{ color: _pT }}>{_PC.moneyFull(r.monthlyRevenue)}</span> revenue − <span style={{ color: _pT }}>{_PC.moneyFull(r.monthlyCost)}</span> cost = <span style={{ color: flag, fontWeight: 700 }}>{_PC.moneyFull(r.monthlyProfit)}</span> / mo<br />
        <span style={{ color: flag, fontWeight: 700 }}>{_PC.moneyFull(r.monthlyProfit)}</span> ÷ <span style={{ color: _pT }}>{Math.round(r.hours) || 0} hrs/mo</span> = <span style={{ color: flag, fontWeight: 700 }}>{_PC.moneyFull(r.effHourly)}/hr</span> · margin <span style={{ color: _pT }}>{Math.round(r.marginPct)}%</span>
      </div>

      {layout === 'cards' ?
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
          <StatCard label="Effective hourly" value={`${_PC.moneyFull(r.effHourly)}`} color={flag} sub="your time, after costs" />
          <StatCard label="Monthly profit" value={_PC.money(r.monthlyProfit)} color={accent} sub={`${Math.round(r.marginPct)}% margin`} />
          {!isHour && <StatCard label={`Profit / ${r.unitLabel}`} value={_PC.moneyFull(r.profitPerUnit)} sub={`you charge ${_PC.moneyFull(r.price)}`} />}
          {isHour && <StatCard label="Your rate" value={`${_PC.moneyFull(r.price)}/hr`} sub={`${Math.round(r.hours)} billable hrs/mo`} />}
          <StatCard label="If you raised 20%" value={`${_PC.moneyFull(r.scenarioHourly)}/hr`} color={accent} sub={`charge ${_PC.moneyFull(r.scenarioPrice)}${perU}`} />
        </div> :

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <div style={{ fontFamily: _pF, fontSize: 9.5, letterSpacing: 1.5, color: accent }}>WHERE YOUR PRICE SITS · PER {r.unitLabel.toUpperCase()}</div>
          <BarRow label={`Cost to deliver`} value={r.costPerUnit} max={max} color="rgba(236,237,241,0.35)" valueText={_PC.moneyFull(r.costPerUnit)} onInfo={onInfo} info={`What delivering one ${r.unitLabel} costs you (your monthly cost split across volume). Charge below this and you lose money.`} />
          <BarRow label="You charge" value={r.price} max={max} color={flag} valueText={_PC.moneyFull(r.price)} emphasis onInfo={onInfo} info={`Your price per ${r.unitLabel}. After costs, your own time earns ${_PC.moneyFull(r.effHourly)}/hr at a ${Math.round(r.marginPct)}% margin.`} />
          <BarRow label="If you raised 20%" value={r.scenarioPrice} max={max} color={accent} valueText={_PC.moneyFull(r.scenarioPrice)} emphasis onInfo={onInfo} info={`A 20% raise would lift your effective rate to ${_PC.moneyFull(r.scenarioHourly)}/hr and your monthly profit to ${_PC.moneyFull(r.scenarioProfit)}.`} />
        </div>
      }
      <Takeaway take={r.take} accent={accent} />
      <ReportUnlock accent={accent} tool="Price-It"
        resultHash={_PC.hashResult('price:job:' + r.effHourly + ':' + r.price)}
        includes={['The full math, normalised to a month', 'Where your price sits, with charts', 'A margin gauge and a 20% what-if', 'The blunt verdict + how to fix it, as PDF']}
        sections={[{ title: 'How to fix it', ordered: true, items: (r.take && r.take.levers) || [] }]}
        buildSpec={() => window.CST_REPORT.priceReportSpec(r, accent)}
        filename="cs-tech-price-report" />
    </div>);
}

// ----- Mode B: valued business -----
function BizResult({ r, accent, layout, spec, onShare, onInfo }) {
  const max = Math.max(r.high, r.sdeHi, r.revHi) * 1.08 || 1;
  return (
    <div className="cst-scroll" style={{ flex: 1, minHeight: 0, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 14, paddingRight: 2 }}>
      <div>
        <div style={{ fontFamily: _pF, fontSize: 10, letterSpacing: 1.5, color: _pHD, marginBottom: 4 }}>BALLPARK VALUE · {r.industry.label.toUpperCase()}</div>
        <div style={{ fontFamily: _pF, fontWeight: 800, fontSize: 42, color: accent, letterSpacing: -2, lineHeight: 1 }}>{_PC.money(r.likely)}</div>
        <div style={{ fontFamily: _pF, fontSize: 12, color: _pH, marginTop: 5 }}>likely · band {_PC.money(r.low)} – {_PC.money(r.high)}</div>
        <p style={{ margin: '8px 0 0', fontFamily: _pF, fontSize: 13, lineHeight: 1.45, color: _pT, fontWeight: 600 }}>{r.headline}</p>
      </div>

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

      <div style={{ background: _pG, border: `1px solid ${_pHR}`, borderRadius: 10, padding: '10px 12px', fontFamily: _pF, fontSize: 11.5, color: _pH, lineHeight: 1.7 }}>
        profit <span style={{ color: _pT }}>{_PC.money(r.sde)}</span> × <span style={{ color: _pT }}>{r.industry.sde[0]}–{r.industry.sde[1]}×</span> = <span style={{ color: accent, fontWeight: 700 }}>{_PC.money(r.sdeLo)}–{_PC.money(r.sdeHi)}</span><br />
        revenue <span style={{ color: _pT }}>{_PC.money(r.revenue)}</span> × <span style={{ color: _pT }}>{r.industry.rev[0]}–{r.industry.rev[1]}×</span> = <span style={{ color: accent, fontWeight: 700 }}>{_PC.money(r.revLo)}–{_PC.money(r.revHi)}</span>
      </div>

      {layout === 'cards' ?
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
          <StatCard label="On profit (SDE)" value={`${_PC.money(r.sdeLo)}–${_PC.money(r.sdeHi)}`} sub={`${r.industry.sde[0]}–${r.industry.sde[1]}× SDE`} />
          <StatCard label="On revenue" value={`${_PC.money(r.revLo)}–${_PC.money(r.revHi)}`} sub={`${r.industry.rev[0]}–${r.industry.rev[1]}× revenue`} />
          <StatCard label="Effective multiple" value={r.effMultiple ? `${r.effMultiple.toFixed(1)}×` : '—'} color={accent} sub="of owner profit" />
          <StatCard label="Profit margin" value={r.profitMargin != null ? `${Math.round(r.profitMargin)}%` : '—'} sub="profit ÷ revenue" />
        </div> :

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <div style={{ fontFamily: _pF, fontSize: 9.5, letterSpacing: 1.5, color: accent }}>TWO WAYS TO VALUE IT</div>
          <BarRow label="On profit (SDE × multiple)" value={r.sdeMid} max={max} color={accent} valueText={`${_PC.money(r.sdeLo)}–${_PC.money(r.sdeHi)}`} emphasis onInfo={onInfo} info={`Buyers pay a multiple of owner profit. At ${r.industry.sde[0]}–${r.industry.sde[1]}× your ${_PC.money(r.sde)} SDE, that's this range.`} />
          <BarRow label="On revenue (× multiple)" value={r.revMid} max={max} color={_pS.cold} valueText={`${_PC.money(r.revLo)}–${_PC.money(r.revHi)}`} onInfo={onInfo} info={`A cross-check using ${r.industry.rev[0]}–${r.industry.rev[1]}× revenue. Useful when profit is lumpy, but profit usually matters more.`} />
          <BarRow label="Blended — likely" value={r.likely} max={max} color={_pS.good} valueText={_PC.money(r.likely)} emphasis onInfo={onInfo} info="A weighted blend of both methods — profit-led, since that's what most buyers actually pay for. Your realistic starting point." />
        </div>
      }
      <div style={{ fontFamily: _pF, fontSize: 10.5, color: _pHD, lineHeight: 1.4, fontStyle: 'italic' }}>A rule-of-thumb band, not a formal appraisal — your real number depends on growth, risk, and who’s buying.</div>
      <Takeaway take={r.take} accent={accent} />
      <ReportUnlock accent={accent} tool="Price-It"
        resultHash={_PC.hashResult('price:biz:' + r.likely + ':' + r.revenue)}
        includes={['Both valuation methods, with charts', 'Your effective multiple and margin', 'A profit-margin gauge', 'How to raise the number, as PDF']}
        sections={[{ title: 'How to raise the number', ordered: true, items: (r.take && r.take.levers) || [] }]}
        buildSpec={() => window.CST_REPORT.priceReportSpec(r, accent)}
        filename="cs-tech-valuation-report" />
    </div>);
}

function PriceTool({ active, sim, accent, onExit, onBook, priceLayout = 'bars', onShare, onOpenTool, decisionCtx, setDecisionCtx }) {
  const c0 = accent[0];
  const [sub, setSub] = _puS('mode'); // mode | session | analyze | result
  const [mode, setMode] = _puS(null); // 'job' | 'biz'
  const [result, setResult] = _puS(null);
  const [booked, setBooked] = _puS(false);
  const [barInfo, setBarInfo] = _puS(null);
  const run = useStrategistRun();

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

  // restore saved result from localStorage on mount
  _puE(() => {
    if (!active) return;
    try {
      const saved = JSON.parse(localStorage.getItem('cst_result_price'));
      if (saved && saved.result) {
        setMode(saved.mode); setResult(saved.result); setSub('result');
      }
    } catch (e) {}
  }, [active]);

  const compute = (m, ans) => m === 'job' ? _PD.priceJob(ans) : _PD.valueBusiness(ans);

  const finish = (m) => (ans) => {
    setSub('analyze');setResult(null);setBooked(false);
    const build = async () => {
      const r = compute(m, ans);
      const raw = await _PC.askAI(_PD.takeawayPrompt(r));
      r.take = _PD.parseTakeaway(raw) || _PD.heuristicTakeaway(r);
      return r;
    };
    run.start({ sim, lines: m === 'job' ? JOB_LINES : BIZ_LINES,
      nodes: m === 'job' ? ['Cost', 'Time', 'Margin', 'Comps', 'Value', 'Price'] : ['Profit', 'Revenue', 'Multiple', 'Risk', 'Buyers', 'Band'],
      build, minBeat: 2600, onReady: (r) => {const rr = r || compute(m, ans); setResult(rr);setSub('result');window.CST_STATS.bumpRun('price');try { localStorage.setItem('cst_result_price', JSON.stringify({ mode: m, result: rr })); } catch (e) {}} });
  };

  const pickMode = (m) => {setMode(m);setSub('session');};
  const restart = () => {setMode(null);setResult(null);setBooked(false);setBarInfo(null);setSub('mode');try { localStorage.removeItem('cst_result_price'); } catch (e) {}if (sim) {sim.seedAmbient(22);sim.setMode('ambient');}};

  if (!active) return null;
  const steps = mode === 'job' ? _PD.JOB_STEPS : _PD.BIZ_STEPS;

  return (
    <React.Fragment>
      {/* MODE SELECT */}
      <StageCard active={sub === 'mode'} dir="right" label="Price-It · mode">
        <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none', background: 'linear-gradient(180deg, rgba(15,17,21,0.92) 0%, rgba(15,17,21,0.55) 32%, rgba(15,17,21,0.5) 58%, rgba(15,17,21,0.96) 100%)' }} />
        <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}>Price-It</Eyebrow>
            <h2 style={{ margin: 0, fontFamily: _pF, fontWeight: 700, fontSize: 24, letterSpacing: -0.6, color: _pT }}>What are we pricing?</h2>
            <p style={{ margin: 0, fontFamily: _pF, fontSize: 12, color: _pH, lineHeight: 1.4 }}>Either way, you’ll see the math — and the blunt takeaway.</p>
            {decisionCtx ?
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 7, padding: '8px 11px', borderRadius: 10, background: _pG, border: `1px solid ${_pHR}` }}>
                <span style={{ color: c0, fontSize: 11, flexShrink: 0 }}>↳</span>
                <span style={{ fontFamily: _pF, fontSize: 11.5, color: _pH, lineHeight: 1.4 }}>Continuing with <span style={{ color: _pT, fontWeight: 600 }}>{decisionCtx.length > 52 ? decisionCtx.slice(0, 50) + '…' : decisionCtx}</span></span>
              </div> :
            null}
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
            <ChoiceCard glyph="$" label="Price a job, product, or service" sub="Find your true hourly rate and a price that hits target" accent={c0} onPick={() => pickMode('job')} />
            <ChoiceCard glyph="▣" label="Value a business" sub="A ballpark valuation band from your profit & revenue" accent={accent[1]} onPick={() => pickMode('biz')} />
          </div>
        </div>
      </StageCard>

      {/* SESSION */}
      <StageCard active={sub === 'session'} dir="right" label="Price-It · inputs">
        <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) 32%, rgba(15,17,21,0.55) 60%, rgba(15,17,21,0.96) 100%)' }} />
        <div style={{ position: 'relative', height: '100%' }}>
          {sub === 'session' &&
          <ConversationFlow steps={steps} accent={accent} eyebrow={mode === 'job' ? 'Price-It · price a job' : 'Price-It · value a business'} advisorName="ADVISOR"
          onComplete={finish(mode)} />
          }
        </div>
      </StageCard>

      {/* RESULT */}
      <StageCard active={sub === 'result'} dir="up" label="Price-It · result">
        <Scrim from={0.0} to={0.97} />
        {result &&
        <div style={{ position: 'relative', height: '100%', display: 'flex', flexDirection: 'column', padding: '0 22px 22px', gap: 13 }}>
            <Eyebrow color={c0}>Price-It · {mode === 'job' ? 'your price read' : 'your valuation'}</Eyebrow>
            {mode === 'job' ?
          <JobResult r={result} accent={c0} layout={priceLayout} spec={window.CST_SHARE.priceJobSpec(result, c0)} onShare={onShare} onInfo={setBarInfo} /> :
          <BizResult r={result} accent={c0} layout={priceLayout} spec={window.CST_SHARE.priceBizSpec(result, c0)} onShare={onShare} onInfo={setBarInfo} />}
            <HandoffRow currentId="price" accent={c0} onGo={(id) => onOpenTool && onOpenTool(id)} />
            <ArtifactCTA accent={c0} tool="Price-It" onRestart={restart} restartLabel="Price something else"
          onBook={onBook} />
            <InfoCard info={barInfo} accent={c0} onClose={() => setBarInfo(null)} />
          </div>
        }
      </StageCard>

      {run.analyzing && <AnalyzeOverlay lines={mode === 'job' ? JOB_LINES : BIZ_LINES} idx={run.statusIdx} accent={c0} count={run.count} countNoun="numbers crunched" />}
    </React.Fragment>);
}

const JOB_LINES = ['Adding up your real costs…', 'Counting the hours honestly…', 'Finding your effective rate…', 'Checking it against target…', 'Writing the hard truth…'];
const BIZ_LINES = ['Reading your profit…', 'Applying industry multiples…', 'Cross-checking on revenue…', 'Blending the methods…', 'Writing the hard truth…'];

window.PriceTool = PriceTool;