import { useState } from "react";
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, ReferenceLine } from "recharts";

// ─────────────────────────────────────────────────────────────────────────────
// ROI Replay Player — Sales Demo
// ValueLogics.ai LLC · Enterprise Refactoring · Two Business Areas
// SYNTHETIC DEMO DATA — clearly labeled throughout
// Replace with real D1 data via /roi-watch/actuals at integration
// ─────────────────────────────────────────────────────────────────────────────

const NAVY  = "#0F1E3C";
const TEAL  = "#0D9488";
const BLUE  = "#1D4ED8";
const AMBER = "#D97706";
const GREEN = "#15803D";
const RED   = "#DC2626";
const GRAY  = "#64748B";

// ── Synthetic demo data ──────────────────────────────────────────────────────

const months = ["M1","M2","M3","M4","M5","M6","M7","M8","M9","M10","M11","M12",
                 "M13","M14","M15","M16","M17","M18"];

function genRefactoringData() {
  // BAU: 40 hrs/week on AI prompt coding + rework · 23% defect rate
  // Target: 84% code reduction → 6 hrs/week · 3% defect rate
  return months.map((m, i) => {
    const t = i / 17;
    const projHours    = Math.round(40 - (40 - 7) * t);
    const actualHours  = Math.round(40 - (40 - 6) * t + Math.sin(i * 0.7) * 1.2);
    const projDefects  = Math.round(23 - (23 - 4) * t);
    const actualDefects= Math.round(23 - (23 - 3) * t + Math.cos(i * 0.5) * 0.8);
    const projValue    = Math.round((40 - projHours) * 150 * 4 + (23 - projDefects) * 2200);
    const actualValue  = Math.round((40 - actualHours) * 150 * 4 + (23 - actualDefects) * 2200);
    return { month: m, projHours, actualHours, projDefects, actualDefects,
             projValue, actualValue,
             drift: actualValue >= projValue ? "on_track" : "at_risk" };
  });
}

function genMaintenanceData() {
  // BAU: 60% time on maintenance · cloud bill $18K/month
  // Target: 20% maintenance · cloud bill $4K/month (84% code reduction)
  return months.map((m, i) => {
    const t = i / 17;
    const projMaint    = Math.round(60 - (60 - 22) * t);
    const actualMaint  = Math.round(60 - (60 - 20) * t + Math.sin(i * 0.6) * 1.5);
    const projCloud    = Math.round(18000 - (18000 - 4500) * t);
    const actualCloud  = Math.round(18000 - (18000 - 4000) * t + Math.cos(i * 0.8) * 300);
    const projValue    = Math.round((60 - projMaint) * 150 * 160 / 100 + (18000 - projCloud));
    const actualValue  = Math.round((60 - actualMaint) * 150 * 160 / 100 + (18000 - actualCloud));
    return { month: m, projMaint, actualMaint, projCloud, actualCloud,
             projValue, actualValue,
             drift: actualValue >= projValue ? "on_track" : "at_risk" };
  });
}

function genESGData() {
  // Cloud bill reduction → compute reduction → carbon reduction
  // Modeled: 1 kWh per $3 cloud spend · 0.4 kg CO2 per kWh
  return months.map((m, i) => {
    const t = i / 17;
    const cloudSaving  = Math.round((18000 - 4000) * t);
    const kwh          = Math.round(cloudSaving / 3);
    const co2kg        = Math.round(kwh * 0.4);
    const projCO2      = Math.round((18000 - 4500) * t / 3 * 0.4);
    return { month: m, co2kg, projCO2, cloudSaving,
             eei: kwh > 0 ? (cloudSaving / kwh).toFixed(2) : "—" };
  });
}

const refData  = genRefactoringData();
const maintData= genMaintenanceData();
const esgData  = genESGData();

// ── Components ───────────────────────────────────────────────────────────────

function DriftBadge({ status }) {
  const cfg = {
    on_track:    { bg: "#D1FAE5", color: GREEN,  label: "on_track ✓" },
    at_risk:     { bg: "#FEF3C7", color: AMBER,  label: "at_risk ⚠️" },
    drifting:    { bg: "#FEE2E2", color: RED,    label: "drifting ✗" },
    pending:     { bg: "#F1F5F9", color: GRAY,   label: "pending …"  },
  }[status] || { bg: "#F1F5F9", color: GRAY, label: status };
  return (
    <span style={{ background: cfg.bg, color: cfg.color, fontSize: 11,
      fontWeight: 600, padding: "3px 10px", borderRadius: 20, fontFamily: "monospace" }}>
      {cfg.label}
    </span>
  );
}

function KPI({ label, value, sub, color = GREEN }) {
  return (
    <div style={{ background: "#F8FAFC", borderRadius: 8, padding: "10px 14px", flex: 1 }}>
      <div style={{ fontSize: 10, color: GRAY, marginBottom: 3 }}>{label}</div>
      <div style={{ fontSize: 18, fontWeight: 700, color }}>{value}</div>
      {sub && <div style={{ fontSize: 10, color: GRAY, marginTop: 2 }}>{sub}</div>}
    </div>
  );
}

function SyntheticBadge() {
  return (
    <div style={{ background: "#FEF3C7", color: AMBER, fontSize: 10, fontWeight: 600,
      padding: "2px 10px", borderRadius: 4, display: "inline-block", marginBottom: 12 }}>
      SYNTHETIC DEMO DATA — illustrative only · replace with live actuals at integration
    </div>
  );
}

function ReplayPanel({ title, subtitle, role, biz_case_id, data, kpis, chartConfig, drift }) {
  const [tab, setTab] = useState(0);
  return (
    <div style={{ border: `1px solid #E2E8F0`, borderRadius: 12, overflow: "hidden",
      marginBottom: 20, fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif" }}>

      {/* Header */}
      <div style={{ background: NAVY, padding: "14px 20px",
        display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
        <div>
          <div style={{ fontSize: 10, color: "#93C5FD", letterSpacing: ".07em",
            marginBottom: 3, fontFamily: "monospace" }}>
            ROI REPLAY · {biz_case_id}
          </div>
          <div style={{ fontSize: 16, fontWeight: 700, color: "#FFFFFF", marginBottom: 2 }}>{title}</div>
          <div style={{ fontSize: 12, color: "#94A3B8" }}>{subtitle}</div>
        </div>
        <DriftBadge status={drift} />
      </div>

      {/* Role + attestation */}
      <div style={{ background: "#F8FAFC", padding: "8px 20px",
        borderBottom: "1px solid #E2E8F0", display: "flex",
        justifyContent: "space-between", alignItems: "center" }}>
        <div style={{ fontSize: 11, color: GRAY }}>
          <span style={{ fontWeight: 600, color: "#334155" }}>Role: </span>{role}
          <span style={{ margin: "0 12px", color: "#CBD5E1" }}>·</span>
          <span style={{ fontWeight: 600, color: "#334155" }}>Period: </span>18 months
          <span style={{ margin: "0 12px", color: "#CBD5E1" }}>·</span>
          <span style={{ fontWeight: 600, color: "#334155" }}>Attestation: </span>Quarterly
        </div>
        <div style={{ fontSize: 10, color: GRAY, fontFamily: "monospace" }}>
          chain_hash: 3f8a…c2d1 ✓
        </div>
      </div>

      {/* KPIs */}
      <div style={{ padding: "14px 20px", display: "flex", gap: 10 }}>
        {kpis.map((k, i) => <KPI key={i} {...k} />)}
      </div>

      {/* Chart tabs */}
      <div style={{ padding: "0 20px" }}>
        <div style={{ display: "flex", gap: 0, borderBottom: "1px solid #E2E8F0", marginBottom: 16 }}>
          {chartConfig.map((c, i) => (
            <button key={i} onClick={() => setTab(i)} style={{
              padding: "7px 16px", fontSize: 11, fontWeight: tab === i ? 700 : 400,
              color: tab === i ? BLUE : GRAY,
              background: "none", border: "none",
              borderBottom: tab === i ? `2px solid ${BLUE}` : "2px solid transparent",
              cursor: "pointer", marginBottom: -1
            }}>
              {c.label}
            </button>
          ))}
        </div>

        <div style={{ height: 220, marginBottom: 16 }}>
          <ResponsiveContainer width="100%" height="100%">
            <LineChart data={data} margin={{ top: 4, right: 16, bottom: 0, left: 0 }}>
              <CartesianGrid strokeDasharray="3 3" stroke="#F1F5F9" />
              <XAxis dataKey="month" tick={{ fontSize: 10, fill: GRAY }}
                interval={2} />
              <YAxis tick={{ fontSize: 10, fill: GRAY }}
                tickFormatter={v => chartConfig[tab].yFormat ? chartConfig[tab].yFormat(v) : v} />
              <Tooltip
                formatter={(val, name) => [
                  chartConfig[tab].tooltipFormat ? chartConfig[tab].tooltipFormat(val) : val,
                  name
                ]}
                contentStyle={{ fontSize: 11, borderRadius: 8 }} />
              <Legend wrapperStyle={{ fontSize: 11 }} />
              {chartConfig[tab].lines.map((l, i) => (
                <Line key={i} type="monotone" dataKey={l.key} name={l.name}
                  stroke={l.color} strokeWidth={l.dashed ? 1.5 : 2.5}
                  strokeDasharray={l.dashed ? "6 4" : undefined}
                  dot={false} activeDot={{ r: 4 }} />
              ))}
              {chartConfig[tab].refLines?.map((r, i) => (
                <ReferenceLine key={i} x={r.x} stroke={AMBER}
                  strokeDasharray="4 2"
                  label={{ value: r.label, fontSize: 9, fill: AMBER, position: "top" }} />
              ))}
            </LineChart>
          </ResponsiveContainer>
        </div>
      </div>

      {/* Footer */}
      <div style={{ padding: "10px 20px", background: "#F8FAFC",
        borderTop: "1px solid #E2E8F0", display: "flex",
        justifyContent: "space-between", alignItems: "center" }}>
        <div style={{ fontSize: 10, color: GRAY }}>
          ValueLogics.ai LLC · ROI Replay · Immutable ledger · Bilateral attestation ready
        </div>
        <div style={{ fontSize: 10, color: BLUE, fontFamily: "monospace" }}>
          /replay/{biz_case_id}
        </div>
      </div>
    </div>
  );
}

// ── Main export ───────────────────────────────────────────────────────────────

export default function ROIReplayPlayer() {
  const [showESG, setShowESG] = useState(false);

  // Cumulative value for refactoring
  const refCumulative = refData.map((d, i) => ({
    ...d,
    cumActual:  refData.slice(0,i+1).reduce((s,r) => s + r.actualValue, 0),
    cumProj:    refData.slice(0,i+1).reduce((s,r) => s + r.projValue, 0),
  }));

  // Cumulative value for maintenance
  const maintCumulative = maintData.map((d, i) => ({
    ...d,
    cumActual: maintData.slice(0,i+1).reduce((s,r) => s + r.actualValue, 0),
    cumProj:   maintData.slice(0,i+1).reduce((s,r) => s + r.projValue, 0),
  }));

  const totalRefValue  = refData.reduce((s,d) => s + d.actualValue, 0);
  const totalMaintValue= maintData.reduce((s,d) => s + d.actualValue, 0);
  const totalCO2       = esgData.reduce((s,d) => s + d.co2kg, 0);

  return (
    <div style={{ padding: 24, maxWidth: 780, margin: "0 auto",
      fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",
      background: "#fff" }}>

      {/* Page header */}
      <div style={{ marginBottom: 20 }}>
        <div style={{ fontSize: 11, color: GRAY, letterSpacing: ".07em", marginBottom: 4 }}>
          ROI DRIFTWATCH PORTAL · ENTERPRISE REFACTORING
        </div>
        <div style={{ fontSize: 22, fontWeight: 700, color: NAVY, marginBottom: 4 }}>
          ROI Replay — Refactoring Engagement
        </div>
        <div style={{ fontSize: 13, color: GRAY, marginBottom: 12 }}>
          2 business cases · 2 roles · 2 assets · 18-month engagement
        </div>
        <SyntheticBadge />

        {/* Portfolio summary */}
        <div style={{ display: "flex", gap: 10, marginTop: 12 }}>
          <KPI label="Total value delivered" value={`$${(totalRefValue + totalMaintValue).toLocaleString()}`}
            sub="Refactoring + Maintenance combined" color={GREEN} />
          <KPI label="Refactoring savings" value={`$${totalRefValue.toLocaleString()}`}
            sub="Defects avoided + hours recovered" color={BLUE} />
          <KPI label="Maintenance savings" value={`$${totalMaintValue.toLocaleString()}`}
            sub="Cloud bill + maintenance hours" color={TEAL} />
          {showESG && <KPI label="CO₂ avoided" value={`${(totalCO2/1000).toFixed(1)}t`}
            sub="Cloud compute reduction · ESG proof" color={GREEN} />}
        </div>
      </div>

      {/* REPLAY 1 — Refactoring */}
      <ReplayPanel
        title="Avoid Refactoring Costs"
        subtitle="Move from AI-assisted code sprawl to value-controlled generation — production-ready in as little as one day"
        role="Legacy Refactoring Developers"
        biz_case_id="REF-001"
        data={refCumulative}
        drift="on_track"
        kpis={[
          { label: "Hours recovered (18mo)", value: `${refData.reduce((s,d)=>s+(40-d.actualHours),0).toLocaleString()} hrs`,
            sub: "40 hrs/wk → 6 hrs/wk", color: GREEN },
          { label: "Defects eliminated", value: refData.reduce((s,d)=>s+(23-d.actualDefects),0) + " incidents",
            sub: "23% → 3% defect rate", color: BLUE },
          { label: "Value delivered", value: `$${totalRefValue.toLocaleString()}`,
            sub: `vs $${refData.reduce((s,d)=>s+d.projValue,0).toLocaleString()} projected`, color: GREEN },
          { label: "DriftWatch", value: "on_track ✓", sub: "All 18 periods in compliance", color: GREEN },
        ]}
        chartConfig={[
          {
            label: "Cumulative value",
            lines: [
              { key: "cumActual", name: "Actual value", color: GREEN },
              { key: "cumProj",   name: "Projected",    color: BLUE, dashed: true },
            ],
            yFormat: v => "$" + (v/1000).toFixed(0) + "K",
            tooltipFormat: v => "$" + v.toLocaleString(),
            refLines: [{ x: "M6", label: "Q2 attestation" }, { x: "M12", label: "Q4 attestation" }],
          },
          {
            label: "Hours/week",
            lines: [
              { key: "actualHours", name: "Actual hours", color: GREEN },
              { key: "projHours",   name: "Projected",    color: BLUE, dashed: true },
            ],
            yFormat: v => v + " hrs",
            tooltipFormat: v => v + " hrs/week",
          },
          {
            label: "Defect rate",
            lines: [
              { key: "actualDefects", name: "Actual defects %", color: RED },
              { key: "projDefects",   name: "Projected",         color: AMBER, dashed: true },
            ],
            yFormat: v => v + "%",
            tooltipFormat: v => v + "% defect rate",
          },
        ]}
      />

      {/* REPLAY 2 — Maintenance */}
      <ReplayPanel
        title="Reduce Maintenance Costs"
        subtitle="Increase Logic Density Ratio — leaner code, smaller surface area, lower cloud bill"
        role="Application Developers"
        biz_case_id="REF-002"
        data={maintCumulative}
        drift="on_track"
        kpis={[
          { label: "Maintenance time recovered", value: `${maintData.reduce((s,d)=>s+(60-d.actualMaint),0)}%`,
            sub: "60% → 20% maintenance time", color: GREEN },
          { label: "Cloud bill saved (18mo)", value: `$${maintData.reduce((s,d)=>s+(18000-d.actualCloud),0).toLocaleString()}`,
            sub: "$18K/mo → $4K/mo", color: TEAL },
          { label: "Value delivered", value: `$${totalMaintValue.toLocaleString()}`,
            sub: "Hours + cloud combined", color: GREEN },
          { label: "DriftWatch", value: "on_track ✓", sub: "All 18 periods in compliance", color: GREEN },
        ]}
        chartConfig={[
          {
            label: "Cumulative value",
            lines: [
              { key: "cumActual", name: "Actual value", color: TEAL },
              { key: "cumProj",   name: "Projected",    color: BLUE, dashed: true },
            ],
            yFormat: v => "$" + (v/1000).toFixed(0) + "K",
            tooltipFormat: v => "$" + v.toLocaleString(),
            refLines: [{ x: "M6", label: "Q2 attestation" }, { x: "M12", label: "Q4 attestation" }],
          },
          {
            label: "Cloud bill",
            lines: [
              { key: "actualCloud", name: "Actual cloud bill", color: TEAL },
              { key: "projCloud",   name: "Projected",          color: BLUE, dashed: true },
            ],
            yFormat: v => "$" + (v/1000).toFixed(0) + "K",
            tooltipFormat: v => "$" + v.toLocaleString() + "/mo",
          },
          {
            label: "Maintenance %",
            lines: [
              { key: "actualMaint", name: "Actual maintenance %", color: AMBER },
              { key: "projMaint",   name: "Projected",              color: BLUE, dashed: true },
            ],
            yFormat: v => v + "%",
            tooltipFormat: v => v + "% of eng time",
          },
        ]}
      />

      {/* ESG Bonus */}
      <div style={{ border: "1px solid #D1FAE5", borderRadius: 12, overflow: "hidden",
        marginBottom: 20 }}>
        <div style={{ background: "#064E3B", padding: "12px 20px",
          display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <div>
            <div style={{ fontSize: 10, color: "#6EE7B7", letterSpacing: ".07em",
              marginBottom: 2, fontFamily: "monospace" }}>
              ESG DUAL-PROOF · EnvironmentalEfficiencyIndex
            </div>
            <div style={{ fontSize: 15, fontWeight: 700, color: "#fff" }}>
              Carbon Reduction via Cloud Bill Savings
            </div>
            <div style={{ fontSize: 11, color: "#6EE7B7" }}>
              Economic ROI + Environmental ROI · same governed contract
            </div>
          </div>
          <button onClick={() => setShowESG(!showESG)} style={{
            background: showESG ? "#6EE7B7" : "transparent",
            color: showESG ? "#064E3B" : "#6EE7B7",
            border: "1px solid #6EE7B7", borderRadius: 6,
            padding: "5px 14px", fontSize: 11, fontWeight: 600, cursor: "pointer"
          }}>
            {showESG ? "Hide" : "Show ESG proof"}
          </button>
        </div>

        {showESG && (
          <div style={{ padding: 20 }}>
            <SyntheticBadge />
            <div style={{ fontSize: 11, color: GRAY, marginBottom: 12, marginTop: 8 }}>
              Modeled: 1 kWh per $3 cloud spend · 0.4 kg CO₂ per kWh · Cloud bill reduction → compute reduction → carbon reduction
            </div>
            <div style={{ display: "flex", gap: 10, marginBottom: 16 }}>
              <KPI label="CO₂ avoided (18mo)" value={`${(totalCO2/1000).toFixed(1)}t`}
                sub="Via cloud bill reduction" color="#059669" />
              <KPI label="Compute saved" value={`${(totalCO2/0.4/1000).toFixed(0)}K kWh`}
                sub="$3 cloud = 1 kWh modeled" color="#059669" />
              <KPI label="EEI score" value="↑ 4.2×"
                sub="Business value per compute unit" color="#059669" />
            </div>
            <div style={{ height: 180 }}>
              <ResponsiveContainer width="100%" height="100%">
                <LineChart data={esgData} margin={{ top: 4, right: 16, bottom: 0, left: 0 }}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#D1FAE5" />
                  <XAxis dataKey="month" tick={{ fontSize: 10, fill: GRAY }} interval={2} />
                  <YAxis tick={{ fontSize: 10, fill: GRAY }}
                    tickFormatter={v => v + " kg"} />
                  <Tooltip formatter={v => [v + " kg CO₂", "Carbon avoided"]}
                    contentStyle={{ fontSize: 11, borderRadius: 8 }} />
                  <Legend wrapperStyle={{ fontSize: 11 }} />
                  <Line type="monotone" dataKey="co2kg" name="Actual CO₂ avoided"
                    stroke="#059669" strokeWidth={2.5} dot={false} activeDot={{ r: 4 }} />
                  <Line type="monotone" dataKey="projCO2" name="Projected"
                    stroke="#6EE7B7" strokeWidth={1.5} strokeDasharray="6 4"
                    dot={false} />
                </LineChart>
              </ResponsiveContainer>
            </div>
          </div>
        )}
      </div>

      {/* Footer */}
      <div style={{ textAlign: "center", fontSize: 11, color: GRAY,
        borderTop: "1px solid #E2E8F0", paddingTop: 14, fontStyle: "italic" }}>
        "An immutable, self-governing economic operating system where technology is mathematically chained to value creation."
        <br />
        <span style={{ fontStyle: "normal", fontWeight: 600, color: NAVY }}>
          ValueLogics.ai LLC · as@valuelogics.ai · +1 (728) 230-5573
        </span>
      </div>
    </div>
  );
}
