// ROI Calculator — in-app view. Reacts to the global showroom / designer / date
// filters because App.jsx feeds it the already-filtered deals, contacts and reps.
// All maths lives in window.useROICalculator (components/ROICalculator.jsx);
// this file is purely presentation.
//
// Layout: three sections — Revenue Impact, Time & Efficiency, Your ROI — each led
// by large headline numbers, plus a "What if" recovery scenario.
function ROI({ deals, contacts, reps, stages, targets, plan, onChangePlan, hourlyRate, onChangeHourlyRate, scopeLabel }) {
  const planPricing = window.ROI_PLAN_PRICING;
  const PLAN_IDS = ['free', 'starter', 'growth', 'scale', 'enterprise'];
  const fmt = window.fmt;

  const STAGE_LABEL = {};
  (stages || []).forEach(s => { STAGE_LABEL[s.id] = s.label; });
  const stageColor = (id) => `var(--s-${id}, var(--ink-3))`;

  const roi = window.useROICalculator({ deals, contacts, reps, targets, plan, stages, hourlyRate });
  const { raw, formatted, inputs, assumptions, breakdown } = roi;
  const maxWeighted = Math.max(1, ...breakdown.weightedByStage.map(s => s.weighted));

  // "What if" — recover just 20% of the raw value sitting in stuck deals.
  const RECOVER_SHARE = 0.20;
  const whatIfGain = raw.stuckPipelineRaw * RECOVER_SHARE;

  const Stat = ({ label, value, foot, variant, sub }) => (
    <div className={"roi-stat" + (variant ? " " + variant : "") + (sub ? " sub" : "")}>
      <div className="roi-stat-lbl">{label}</div>
      <div className="roi-stat-val">{value}</div>
      {foot && <div className="roi-stat-foot">{foot}</div>}
    </div>
  );

  const Section = ({ eyebrow, title, note, children }) => (
    <div className="roi-section">
      <div className="roi-section-hd">
        <span className="roi-eyebrow">{eyebrow}</span>
        <span className="roi-section-title">{title}</span>
        {note && <span className="roi-section-note">{note}</span>}
      </div>
      {children}
    </div>
  );

  return (
    <div className="roi-view">
      {/* Plan / billing controls */}
      <div className="roi-controls">
        <div>
          <div className="roi-ctrl-label">Plan</div>
          <div className="roi-seg">
            {PLAN_IDS.map(p => (
              <button key={p} className={plan === p ? 'on' : ''} onClick={() => onChangePlan(p)}>
                {planPricing[p].name}
                <span className="px">${planPricing[p].pricePerSeat}</span>
              </button>
            ))}
          </div>
        </div>
        <div style={{ marginLeft: 'auto' }}>
          <div className="roi-ctrl-label">Billing</div>
          <div className="roi-billing">
            <strong>{inputs.seats} seat{inputs.seats === 1 ? '' : 's'}</strong> × ${planPricing[plan].pricePerSeat}/mo
            {' = '}<strong>{formatted.monthlyCrmCost}/mo</strong>
          </div>
        </div>
      </div>

      {/* ============ 1 · REVENUE IMPACT ============ */}
      <Section
        eyebrow="01"
        title="Revenue Impact"
        note={`${inputs.openDealCount.toLocaleString()} open deals${scopeLabel ? ' · ' + scopeLabel : ''}`}
      >
        <div className="roi-stats cols-3">
          <Stat
            label="Pipeline value"
            value={formatted.pipelineValue}
            foot={<span className="mono">Σ value of {inputs.openDealCount} open deals</span>}
          />
          <Stat
            label="Projected 90-day revenue"
            value={formatted.projected90DayRevenue}
            foot={<span className="mono">Σ value × stage win-rate, closing ≤ {assumptions.horizonDays}d</span>}
          />
          <Stat
            label="Revenue at risk"
            value={formatted.revenueAtRisk}
            variant="risk"
            foot={<span className="mono">{raw.stuckDealCount} deals idle ≥ {assumptions.stuckDays}d ({formatted.stuckPipelineRaw} raw)</span>}
          />
        </div>

        <div className="roi-panel" style={{ marginTop: 12 }}>
          <div className="roi-panel-hd">
            <div className="roi-panel-title">Weighted pipeline by stage</div>
            <div className="roi-panel-sub">Open value × win-rate — what feeds the 90-day projection</div>
          </div>
          <div className="roi-panel-body">
            {breakdown.weightedByStage.length === 0 && (
              <div className="empty">No open deals in the current selection.</div>
            )}
            {breakdown.weightedByStage.map(s => (
              <div className="roi-sbar" key={s.stage}>
                <div className="roi-sbar-lbl">
                  <span className="roi-sbar-dot" style={{ background: stageColor(s.stage) }}></span>
                  {STAGE_LABEL[s.stage] || s.stage}
                  <span className="roi-sbar-wr">{Math.round(s.winRate * 100)}%</span>
                </div>
                <div className="roi-sbar-track">
                  <div className="roi-sbar-fill" style={{ width: (s.weighted / maxWeighted * 100) + '%', background: stageColor(s.stage) }}></div>
                </div>
                <div className="roi-sbar-val">{fmt.money(s.weighted, true)}</div>
              </div>
            ))}
          </div>
        </div>
      </Section>

      {/* ============ 2 · TIME & EFFICIENCY ============ */}
      <Section
        eyebrow="02"
        title="Time & Efficiency"
        note={`${inputs.repCount} ${inputs.repCount === 1 ? 'designer' : 'designers'} · ${inputs.activeContactCount.toLocaleString()} active contacts`}
      >
        <div className="roi-slider">
          <div className="roi-slider-top">
            <div className="lbl">
              Average hourly staff cost
              <small>Blended cost of a sales person's time — drives the productivity dividend</small>
            </div>
            <div className="roi-slider-val">${hourlyRate}<span> / hr</span></div>
          </div>
          <input
            type="range" min="20" max="100" step="5" value={Math.min(100, Math.max(20, hourlyRate))}
            onChange={e => onChangeHourlyRate(Number(e.target.value))}
          />
          <div className="roi-slider-scale"><span>$20</span><span>$100</span></div>
        </div>

        <div className="roi-stats cols-3">
          <Stat
            label="Time saved per week"
            value={formatted.timeSavedHoursPerWeek}
            foot={<span className="mono">{inputs.repCount} × {assumptions.adminHoursSavedPerRepPerWeek}h + deal/contact admin</span>}
          />
          <Stat
            label="Value of time saved"
            value={formatted.costOfTimeSavedPerWeek + " / wk"}
            sub
            foot={<span className="mono">{formatted.timeSavedHoursPerWeek}/wk × ${assumptions.hourlyRate}</span>}
          />
          <Stat
            label="Productivity dividend"
            value={formatted.costOfTimeSavedPerMonth + " / mo"}
            sub
            foot={<span className="mono">weekly value × {assumptions.weeksPerMonth.toFixed(2)} weeks</span>}
          />
        </div>
      </Section>

      {/* ============ 3 · YOUR ROI ============ */}
      <Section eyebrow="03" title="Your ROI" note={`${planPricing[plan].name} plan`}>
        <div className="roi-stats cols-4">
          <Stat
            label="Return on investment"
            value={formatted.roiMultiplier}
            variant="accent"
            foot="Total monthly value ÷ monthly cost"
          />
          <Stat label="Payback period" value={formatted.paybackDays} sub foot="To cover the monthly bill" />
          <Stat label="Total monthly value" value={formatted.totalMonthlyValue} sub foot="Time saved + revenue protected" />
          <Stat label="Monthly cost" value={formatted.monthlyCrmCost} sub foot={`${inputs.seats} seat${inputs.seats === 1 ? '' : 's'} × $${planPricing[plan].pricePerSeat}`} />
        </div>

        <div className="roi-panel" style={{ marginTop: 12 }}>
          <div className="roi-panel-hd">
            <div className="roi-panel-title">How total monthly value is built</div>
            <div className="roi-panel-sub">Every dollar traced to a documented formula</div>
          </div>
          <div className="roi-panel-body">
            <div className="roi-vbuild">
              <div className="roi-vbuild-row">
                <span className="lbl">Productivity dividend<small>cost of time saved, per month</small></span>
                <span className="v">{fmt.money(breakdown.monthlyTimeValue)}</span>
              </div>
              <div className="roi-vbuild-row">
                <span className="lbl">Revenue protected<small>{Math.round(assumptions.recoveryRate * 100)}% of at-risk recovered, per month</small></span>
                <span className="v">{fmt.money(breakdown.monthlyRecoveredRevenue)}</span>
              </div>
              <div className="roi-vbuild-row total">
                <span className="lbl">Total monthly value</span>
                <span className="v">{formatted.totalMonthlyValue}</span>
              </div>
            </div>
          </div>
        </div>
      </Section>

      {/* ============ 4 · WHAT-IF SCENARIOS ============ */}
      <Section
        eyebrow="04"
        title="What-If Scenarios"
        note={`Based on your ${formatted.winRate} win rate · ${formatted.avgDealValue} avg deal`}
      >
        <div className="roi-scenarios">
          <div className="roi-scenario">
            <div className="roi-scenario-tag"><span className="n">1</span><span style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-2)' }}>WIN RATE</span></div>
            <div className="roi-scenario-title">Improve win rate by 5 points</div>
            <div className="roi-scenario-val">+{fmt.money(raw.scenarioWinRate)}<span className="unit"> / yr</span></div>
            <div className="roi-scenario-basis">+5 pts on {formatted.winRate} → {Math.round(raw.closedCount * (12 / raw.periodMonths) * assumptions.winRateLiftPts)} more wins/yr × {formatted.avgDealValue} avg deal</div>
          </div>

          <div className="roi-scenario">
            <div className="roi-scenario-tag"><span className="n">2</span><span style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-2)' }}>FOLLOW-UP</span></div>
            <div className="roi-scenario-title">Follow up on all stuck deals within 7 days</div>
            <div className="roi-scenario-val">+{fmt.money(raw.scenarioFollowUp)}<span className="unit"> / yr</span></div>
            <div className="roi-scenario-basis">{raw.stuckDealCount} stuck deals ({formatted.stuckPipelineRaw}) won back at {formatted.winRate}</div>
          </div>

          <div className="roi-scenario">
            <div className="roi-scenario-tag"><span className="n">3</span><span style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-2)' }}>HEADCOUNT</span></div>
            <div className="roi-scenario-title">Add one more sales designer</div>
            <div className="roi-scenario-val">+{fmt.money(raw.scenarioNewRep)}<span className="unit"> / yr</span></div>
            <div className="roi-scenario-basis">avg designer output ({fmt.money(raw.annualWonRevenue / Math.max(1, inputs.repCount))}/yr) × {Math.round(assumptions.newRepRamp * 100)}% year-one ramp</div>
          </div>
        </div>
      </Section>

      {/* ============ QUICK WIN ============ */}
      <div className="roi-whatif">
        <div className="roi-whatif-num">
          <div className="roi-whatif-lbl">What if you recovered 20% of stuck deals?</div>
          <div className="roi-whatif-val">+{fmt.money(whatIfGain)}</div>
        </div>
        <div className="roi-whatif-copy">
          You currently have <strong>{raw.stuckDealCount} deals</strong> worth <strong>{formatted.stuckPipelineRaw}</strong> sitting idle
          for {assumptions.stuckDays}+ days. Win back just <strong>one in five</strong> of them and that's
          {' '}<strong>{fmt.money(whatIfGain)}</strong> of revenue you'd otherwise have left on the table —
          before counting any productivity gains.
          <div className="roi-mrow-formula">{formatted.stuckPipelineRaw} stuck × <span className="eq">20%</span> = {fmt.money(whatIfGain)}</div>
        </div>
      </div>

      {/* Assumptions */}
      <div className="roi-assumptions">
        <h4>Model assumptions — every lever, on the table</h4>
        <ul>
          <li><span>Cost of time</span><b>${assumptions.hourlyRate}/hr</b></li>
          <li><span>Projection horizon</span><b>{assumptions.horizonDays} days</b></li>
          <li><span>Stuck-deal threshold</span><b>{assumptions.stuckDays} days idle</b></li>
          <li><span>At-risk recovery rate</span><b>{Math.round(assumptions.recoveryRate * 100)}%</b></li>
          <li><span>Admin saved / designer / week</span><b>{assumptions.adminHoursSavedPerRepPerWeek} hrs</b></li>
          <li><span>Saved / open deal / week</span><b>{assumptions.minutesSavedPerOpenDealPerWeek} min</b></li>
          <li><span>Saved / active contact / week</span><b>{assumptions.minutesSavedPerContactPerWeek} min</b></li>
          <li><span>Active-contact window</span><b>{assumptions.activeContactDays} days</b></li>
        </ul>
        <p className="note">Win-rates by stage come from your live pipeline stages. Numbers update with the showroom, designer and date-range filters above.</p>
      </div>
    </div>
  );
}

window.ROI = ROI;
