// Strategic Decisions page — single-decision cards with scenarios + AI recommendation

const { useState: useStateDec } = React;

const DECISIONS = [
  {
    id: "D-001",
    title: "Close, relocate, or reposition Cherry Creek?",
    category: "Real estate",
    bizTypes: ["retail"],
    deadline: "Decide by Jun 30",
    horizon: "12-month impact",
    state: "Cherry Creek lost $5.3K last month — it's the only unprofitable store. Foot traffic is 32% below West region average. The lease ends in 8 months with a 90-day notice clause.",
    scenarios: [
      { name: "Status quo", net: -64000, payback: "—", risk: "high", desc: "Continue as-is. Burns $64K/yr at current run rate. Brand presence preserved." },
      { name: "Close + write off", net: 0, payback: "12 mo", risk: "low", desc: "$84K one-time closing cost. Saves $63K/yr. Net zero by month 13.", best: true },
      { name: "Relocate 4 blocks east", net: 92000, payback: "8 mo", risk: "medium", desc: "Cherry Hills corridor has 2.1x your foot traffic. Demos match Pearl District. $48K relocation cost." },
      { name: "Outlet repositioning", net: 28000, payback: "5 mo", risk: "medium", desc: "Lower margin, higher conversion. Tests retail format for slow-moving inventory." },
    ],
    recommendation: "Relocate. Cherry Hills demographics match Pearl District (your best store, $84/sqft). Worst case mirrors your closing scenario. Best case adds $92K of annual profit and tests a denser corridor before committing to expansion.",
    confidence: 78,
    aiReasoning: [
      "Modeled traffic uplift using comparable retail in same trade area (placer.ai pull)",
      "Compared 9-mo trailing performance of Pearl District (similar demos) which runs at $84/sqft vs Cherry Creek at $54/sqft",
      "Stress-tested for −25% revenue downside; still positive vs status quo",
    ],
  },
  {
    id: "D-002",
    title: "Pass V-201 cost increase through to wholesale, or absorb?",
    category: "Pricing",
    bizTypes: ["product", "manufacturing"],
    deadline: "Decide before next price book — Jun 1",
    horizon: "Annualized impact",
    state: "Vendor V-201 raised your input cost on Aurelius Pro Kit by 9% on Apr 18. You haven't changed wholesale price. Margin is down 8.2 pts and costs $52K/month. Your wholesale price is currently 18% below your DTC channel.",
    scenarios: [
      { name: "Absorb the cost", net: -624000, payback: "—", risk: "high", desc: "Margin stays compressed indefinitely. $624K/yr hit. Easiest path, worst outcome." },
      { name: "Full 9% pass-through", net: 624000, payback: "immediate", risk: "medium", desc: "Recover full margin. Risk: wholesale partners push back, some volume loss likely." },
      { name: "Partial 4% pass-through", net: 312000, payback: "immediate", risk: "low", desc: "Still 14% below DTC. Recovers half the margin. Low volume risk per historical price-elasticity.", best: true },
      { name: "Renegotiate with V-201", net: 412000, payback: "30 days", risk: "medium", desc: "Push back on the 9%; offer 2-year commit for 5%. Internal model suggests 65% success likelihood." },
    ],
    recommendation: "Combine: 4% pass-through immediately + open V-201 renegotiation. Pass-through recovers $312K with low volume risk (your DTC arbitrage absorbs most of it). Renegotiation could add another $100–200K. You stay in control either way.",
    confidence: 86,
    aiReasoning: [
      "Wholesale price-elasticity for Aurelius line is −0.4 per historical promo data — minimal volume risk at 4%",
      "DTC margin is 64% vs wholesale 38% — large arbitrage gives pricing headroom",
      "V-201 has lost 2 accounts to your competitor in last 6 months — negotiating leverage present",
    ],
  },
  {
    id: "D-003",
    title: "Liquidate Solas line or hold for ramp-back?",
    category: "Inventory",
    bizTypes: ["product", "manufacturing", "retail"],
    deadline: "Decide by Q3 buy cycle",
    horizon: "Working capital impact",
    state: "Solas (SOL-670, SOL-671) has 14 months of stock on hand. $69K of capital tied up. Sell-through of 12 units/month vs 488 on hand. Last marketing push was 8 months ago.",
    scenarios: [
      { name: "Hold + relaunch", net: -28000, payback: "18+ mo", risk: "high", desc: "Marketing relaunch costs $40K with 30% probability of returning velocity. Carrying cost continues at $8.4K/yr." },
      { name: "Liquidate Channel B at 35% off", net: 46000, payback: "7 mo", risk: "low", desc: "Recovers $46K cash. Frees buy budget for fast-movers. Hits stated MSRP discipline.", best: true },
      { name: "Bundle with fast-movers", net: 22000, payback: "5 mo", risk: "low", desc: "Move 240 units/qtr as add-on. Slower cash recovery but maintains MSRP." },
      { name: "Donate + tax write-off", net: 18000, payback: "tax cycle", risk: "low", desc: "$45K FMV donation = ~$18K tax benefit. Brand-aligned with nonprofit partner." },
    ],
    recommendation: "Liquidate via Channel B. Holding is a sunk-cost trap — marketing relaunch only has 30% probability of working and burns $40K. The freed capital + recovered cash funds the Polaris Beacon stockout fix, which is a higher-velocity SKU.",
    confidence: 82,
    aiReasoning: [
      "Solas trend has been negative for 11 of last 12 months — no inflection signal in data",
      "Channel B has moved 4 similar-velocity lines in last 18 months at 30–40% off; no brand damage",
      "Polaris Beacon (stockout in 11 days) has 24% margin uplift potential with safety stock",
    ],
  },
  {
    id: "D-004",
    title: "Hire associate to break the utilization bottleneck?",
    category: "Headcount",
    bizTypes: ["service"],
    deadline: "Decide by next pipeline review",
    horizon: "6-month forward",
    state: "Senior consultants are running at 92% utilization (target 80%). Associate level is at 79%. Booked pipeline through Q3 needs +1 senior or +2 associates of capacity. New senior takes 6 months to ramp; new associate takes 8 weeks.",
    scenarios: [
      { name: "Hire 1 senior", net: 184000, payback: "9 mo", risk: "medium", desc: "$285K loaded cost. 6-month ramp. Closes capacity gap by Q4. Higher leverage long-term." },
      { name: "Hire 2 associates", net: 142000, payback: "5 mo", risk: "low", desc: "$220K loaded cost. 8-week ramp. Closes gap by Q2 end. Capacity is correct-sized but requires more senior oversight.", best: true },
      { name: "Use contractors", net: 88000, payback: "immediate", risk: "low", desc: "$420/hr blended. Closes immediate gap but margin compresses 12 pts on contracted hours." },
      { name: "Don't hire — turn work down", net: -120000, payback: "—", risk: "high", desc: "Decline ~$340K of Q3 pipeline. Damages 2 customer relationships likely." },
    ],
    recommendation: "Hire 2 associates. Faster ramp matches the pipeline timing. Cost-per-hour is half the senior's. The senior's role is leverage — you want them deploying associates, not billing themselves. Reassess senior hire in Q4 once pipeline is firmed.",
    confidence: 84,
    aiReasoning: [
      "Pipeline ramp curves better matches associate ramp (8 wk) than senior (6 mo)",
      "Last 4 senior hires took 9–11 months to reach 80% utilization at billable rate",
      "Senior leverage ratio (senior:associate) is currently 1:2 vs industry benchmark 1:3.5 — adding associates moves you toward benchmark",
    ],
  },
  {
    id: "D-005",
    title: "Take 1.5–2% early-pay discount on $84K of bills?",
    category: "Cash management",
    bizTypes: ["product", "manufacturing", "retail", "service"],
    deadline: "Within current pay cycle",
    horizon: "One-cycle decision",
    state: "$84K of bills qualify for 1.5–2% early-payment discounts due in the next 7 days. Cash on hand: $1.82M. Average daily burn: $1.1K net. AR collections expected: $312K next 30 days.",
    scenarios: [
      { name: "Take all discounts", net: 1400, payback: "immediate", risk: "low", desc: "Captures $1.4K margin this cycle. Net cash position unaffected (still $1.74M+ end of cycle).", best: true },
      { name: "Take only the 2% tier", net: 980, payback: "immediate", risk: "low", desc: "More conservative cash mgmt. Captures most of the savings with less cash deployed early." },
      { name: "Skip — preserve cash", net: 0, payback: "—", risk: "low", desc: "Maintains maximum cash reserves. Forgoes $1.4K free margin." },
    ],
    recommendation: "Take all. The decision is symmetric: zero downside cash-position risk (runway is 12+ months), zero implementation cost, $1.4K of free margin. The kind of compounding 1.5–2% optimization that adds 50 bps to net margin over a year.",
    confidence: 96,
    aiReasoning: [
      "Cash position vs operating needs: 11x monthly burn — no liquidity concern",
      "AR collections schedule supports the timing",
      "Effective annualized return of taking the discount: ~36% — substantially above any alternative cash use",
    ],
  },
];

function DecisionsPage({ data, bizType }) {
  const [active, setActive] = useStateDec(0);
  const filtered = DECISIONS.filter(d => d.bizTypes.includes(bizType));
  const decisions = filtered.length > 0 ? filtered : DECISIONS;
  const current = decisions[active] || decisions[0];

  const totalImpact = decisions.reduce((s, d) => {
    const bestScenario = d.scenarios.find(s => s.best);
    return s + (bestScenario ? Math.max(0, bestScenario.net) : 0);
  }, 0);

  return (
    <div className="pc-page">
      <div className="pc-kpi-grid pc-kpi-grid-4">
        <KPICard label="Open decisions"     value={decisions.length} sub={decisions.filter(d => d.deadline.includes("Jun") || d.deadline.includes("cycle")).length + " time-sensitive"} accent="var(--accent-2)" />
        <KPICard label="Recommended impact" value={fmtUSD(totalImpact, { compact: true })} hint="Sum of AI-recommended scenarios" accent="var(--positive)" />
        <KPICard label="Avg AI confidence"  value={Math.round(decisions.reduce((s,d) => s+d.confidence, 0) / decisions.length) + "%"} hint="Across all open decisions" accent="var(--accent)" />
        <KPICard label="Decisions in last 30d" value={4} delta={33.3} sub="3 accepted · 1 deferred" accent="var(--positive)" />
      </div>

      <div className="pc-ai-banner">
        <div style={{ display: "flex", alignItems: "flex-start", gap: 14, flex: 1, minWidth: 0 }}>
          <div style={{ width: 36, height: 36, borderRadius: 10, background: "radial-gradient(circle at 30% 30%, var(--accent), var(--accent-2))", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
            <Icon d={icons.ai} size={18} stroke="var(--on-accent)" strokeWidth={2.4} />
          </div>
          <div>
            <div style={{ fontSize: 11, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: 0.6, marginBottom: 3 }}>This isn't a report — it's a queue of actual decisions</div>
            <div style={{ fontSize: 14, color: "var(--text)", lineHeight: 1.5 }}>
              Each card frames a strategic choice your business is facing, models 2–4 realistic options, attaches dollar impact and risk, and shows what the data recommends. Review them, accept or postpone, and the system tracks the outcome.
            </div>
          </div>
        </div>
      </div>

      {/* Two-column split — list left, detail right */}
      <div className="pc-decisions-shell">
        <div className="pc-decisions-list">
          {decisions.map((d, i) => {
            const bestScenario = d.scenarios.find(s => s.best);
            const impact = bestScenario ? bestScenario.net : 0;
            return (
              <div key={d.id} className={"pc-decision-listrow " + (i === active ? "active" : "")} onClick={() => setActive(i)}>
                <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6 }}>
                  <span className="pc-chip">{d.category}</span>
                  <span style={{ fontSize: 10.5, color: "var(--text-3)" }}>· {d.id}</span>
                </div>
                <div style={{ fontSize: 13.5, fontWeight: 600, lineHeight: 1.35, marginBottom: 8 }}>{d.title}</div>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", fontSize: 11 }}>
                  <span style={{ color: "var(--text-3)" }}>{d.deadline}</span>
                  <span style={{ fontFamily: "ui-monospace, monospace", color: impact > 0 ? "var(--positive)" : "var(--danger)", fontWeight: 500 }}>
                    {impact > 0 ? "+" : ""}{fmtUSD(impact, { compact: true })}
                  </span>
                </div>
              </div>
            );
          })}
        </div>

        <div className="pc-decision-detail">
          {current && <DecisionDetail decision={current} />}
        </div>
      </div>
    </div>
  );
}

function DecisionDetail({ decision }) {
  return (
    <div>
      {/* Header */}
      <div className="pc-decision-hd">
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 8, flexWrap: "wrap" }}>
          <span className="pc-chip">{decision.category}</span>
          <span style={{ fontSize: 11.5, color: "var(--text-3)" }}>{decision.id} · {decision.deadline} · {decision.horizon}</span>
        </div>
        <h2 style={{ fontSize: 26, fontFamily: "'Instrument Serif', serif", fontWeight: 400, margin: 0, lineHeight: 1.2 }}>{decision.title}</h2>
      </div>

      {/* Current state */}
      <div className="pc-decision-section">
        <div className="pc-decision-section-label">Current situation</div>
        <div style={{ fontSize: 14, lineHeight: 1.6, color: "var(--text)" }}>
          {decision.state}
        </div>
      </div>

      {/* Scenarios */}
      <div className="pc-decision-section">
        <div className="pc-decision-section-label">Scenarios · {decision.scenarios.length} options modeled</div>
        <div className="pc-scenarios">
          {decision.scenarios.map((s, i) => (
            <div key={i} className={"pc-scenario " + (s.best ? "best" : "")}>
              {s.best && <div className="pc-scenario-recommended">AI-recommended</div>}
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 14 }}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 6 }}>{s.name}</div>
                  <div style={{ fontSize: 12.5, color: "var(--text-2)", lineHeight: 1.55 }}>{s.desc}</div>
                </div>
                <div style={{ textAlign: "right", flexShrink: 0 }}>
                  <div style={{ fontSize: 22, fontWeight: 600, fontFamily: "ui-monospace, monospace", color: s.net > 0 ? "var(--positive)" : s.net < 0 ? "var(--danger)" : "var(--text-2)" }}>
                    {s.net > 0 ? "+" : s.net < 0 ? "−" : ""}{fmtUSD(Math.abs(s.net), { compact: true })}
                  </div>
                  <div style={{ fontSize: 10.5, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: 0.4 }}>Net impact</div>
                </div>
              </div>
              <div className="pc-scenario-meta">
                <div><span className="pc-scenario-meta-l">Payback</span> <b style={{ fontFamily: "ui-monospace, monospace" }}>{s.payback}</b></div>
                <div>
                  <span className="pc-scenario-meta-l">Risk</span>
                  <span className={"pc-risk-pill pc-risk-" + s.risk}>{s.risk}</span>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* AI Recommendation */}
      <div className="pc-decision-section">
        <div className="pc-decision-section-label">Why Perdura recommends what it does</div>
        <div className="pc-decision-rec">
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
            <div style={{ width: 28, height: 28, borderRadius: 8, background: "radial-gradient(circle at 30% 30%, var(--accent), var(--accent-2))", display: "flex", alignItems: "center", justifyContent: "center" }}>
              <Icon d={icons.ai} size={14} stroke="var(--on-accent)" strokeWidth={2.4} />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 600 }}>Recommendation</div>
              <div style={{ fontSize: 10.5, color: "var(--text-3)" }}>Confidence {decision.confidence}%</div>
            </div>
            <ConfBar v={decision.confidence} />
          </div>
          <div style={{ fontSize: 14, lineHeight: 1.6, color: "var(--text)", marginBottom: 14 }}>{decision.recommendation}</div>
          <div className="pc-decision-section-label" style={{ marginBottom: 8 }}>Reasoning</div>
          <ul className="pc-decision-reasoning">
            {decision.aiReasoning.map((r, i) => <li key={i}>{r}</li>)}
          </ul>
        </div>
      </div>

      {/* Actions */}
      <div className="pc-decision-actions">
        <div style={{ flex: 1 }}>
          <button className="pc-btn ghost">Discuss with team</button>
        </div>
        <button className="pc-btn ghost">Postpone</button>
        <button className="pc-btn ghost">Dismiss</button>
        <button className="pc-btn primary">Accept recommendation</button>
      </div>
    </div>
  );
}

Object.assign(window, { DecisionsPage });
