// ROIScreen.jsx — AegisComply ROI Report

const roiStyles = {
  page: { padding: 24 },
  topRow: { display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 16, marginBottom: 24 },
  kpiCard: { background: 'white', border: '1px solid #E2E8F0', borderRadius: 8, padding: '16px 20px', boxShadow: '0 1px 3px rgba(0,0,0,0.06)' },
  kpiVal: { fontFamily: "'Helvetica',sans-serif", fontSize: 30, fontWeight: 700, lineHeight: 1, marginBottom: 4 },
  kpiLabel: { fontSize: 11, color: '#64748B', textTransform: 'uppercase', letterSpacing: '0.07em', fontWeight: 600 },
  kpiSub: { fontSize: 12, marginTop: 6, fontWeight: 600 },
  insightBox: { background: 'linear-gradient(135deg,#0B1F3A 0%,#1A3558 100%)', borderRadius: 8, padding: '18px 22px', marginBottom: 24, display: 'flex', alignItems: 'center', gap: 16 },
  insightIcon: { width: 44, height: 44, borderRadius: 10, background: 'rgba(13,148,136,0.25)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 },
  insightText: { fontSize: 15, fontWeight: 600, color: 'white', lineHeight: 1.5, flex: 1 },
  insightSub: { fontSize: 12, color: 'rgba(255,255,255,0.55)', marginTop: 2 },
  grid2: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 24 },
  card: { background: 'white', border: '1px solid #E2E8F0', borderRadius: 8, padding: '18px 20px', boxShadow: '0 1px 3px rgba(0,0,0,0.06)' },
  cardTitle: { fontFamily: "'Helvetica',sans-serif", fontSize: 14, fontWeight: 700, color: '#0F172A', marginBottom: 16 },
  compareRow: { display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 },
  compareLabel: { fontSize: 12, color: '#64748B', minWidth: 160 },
  compareBarWrap: { flex: 1, position: 'relative', height: 28, background: '#F1F5F9', borderRadius: 5, overflow: 'hidden' },
  compareBarBefore: { position: 'absolute', left: 0, top: 0, height: '100%', borderRadius: 5, display: 'flex', alignItems: 'center', paddingLeft: 8, fontSize: 11, fontWeight: 600, color: 'white', transition: 'width 0.6s ease' },
  compareBarAfter: { position: 'absolute', left: 0, top: 0, height: '100%', borderRadius: 5, display: 'flex', alignItems: 'center', paddingLeft: 8, fontSize: 11, fontWeight: 600, color: 'white', transition: 'width 0.6s ease' },
  badge: { fontSize: 11, fontWeight: 700, padding: '2px 8px', borderRadius: 4, letterSpacing: '0.04em' },
  trendChart: { width: '100%', height: 160, marginTop: 8 },
  periodBtn: { padding: '5px 12px', borderRadius: 5, fontSize: 12, fontWeight: 500, cursor: 'pointer', border: '1px solid #E2E8F0', background: 'white', color: '#475569', fontFamily: "'DM Sans',sans-serif" },
  periodBtnActive: { background: '#0B1F3A', color: 'white', border: '1px solid #0B1F3A' },
  exportBtn: { height: 36, padding: '0 18px', border: 'none', borderRadius: 6, background: '#0D9488', fontSize: 13, fontWeight: 600, color: 'white', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 7, fontFamily: "'DM Sans',sans-serif" },
  tableCard: { background: 'white', border: '1px solid #E2E8F0', borderRadius: 8, overflow: 'hidden', boxShadow: '0 1px 3px rgba(0,0,0,0.06)', marginBottom: 24 },
  thead: { display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1fr 100px', gap: 8, padding: '9px 16px', background: '#F8FAFC', borderBottom: '1px solid #E2E8F0' },
  trow: { display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1fr 100px', gap: 8, padding: '11px 16px', borderBottom: '1px solid #F1F5F9', alignItems: 'center' },
  thc: { fontSize: 11, fontWeight: 600, letterSpacing: '0.07em', textTransform: 'uppercase', color: '#94A3B8' },
};

const PERIODS = ['3 Months','6 Months','1 Year','All Time'];

const periodData = {
  '3 Months': { saved: 18400, penalty: 4200, downtime: 3, improvement: 34, months: ['Feb','Mar','Apr'], savings: [3200,5800,9400] },
  '6 Months': { saved: 31500, penalty: 8600, downtime: 7, improvement: 52, months: ['Nov','Dec','Jan','Feb','Mar','Apr'], savings: [1200,2800,4100,6200,8900,8300] },
  '1 Year':   { saved: 58200, penalty: 14800, downtime: 15, improvement: 68, months: ['May','Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan','Feb','Mar','Apr'], savings: [800,1400,2200,3600,4800,5200,6100,7400,8200,9400,9600,9500] },
  'All Time': { saved: 72400, penalty: 18200, downtime: 22, improvement: 74, months: ['Q1 25','Q2 25','Q3 25','Q4 25','Q1 26'], savings: [4200,9800,16400,22800,19200] },
};

const compareMetrics = [
  { label: 'Missed calibrations/month', before: 8, after: 0.4, unit: '', format: v => v < 1 ? '<1' : v },
  { label: 'PPE stockouts/month',       before: 5, after: 0.5, unit: '', format: v => v < 1 ? '<1' : v },
  { label: 'Manual audit hours/month',  before: 40, after: 4,  unit: 'h', format: v => `${v}h` },
  { label: 'Compliance score',          before: 51, after: 87,  unit: '%', format: v => `${v}%`, higherIsBetter: true },
  { label: 'Penalty incidents/quarter', before: 3, after: 0,   unit: '', format: v => v === 0 ? 'None' : v },
];

const savingsBreakdown = [
  { category: 'Avoided calibration penalties',  before: 'RM 4,200/qtr',  after: 'RM 0',      saved: 16800, improvement: 100 },
  { category: 'PPE wastage reduction',           before: 'RM 3,100/mo',   after: 'RM 620/mo', saved: 14880, improvement: 80  },
  { category: 'Audit labour hours saved',        before: '40h/mo × RM80', after: '4h/mo',      saved: 23040, improvement: 90  },
  { category: 'Downtime avoidance',             before: '15 days/yr',    after: '1 day/yr',   saved: 18200, improvement: 93  },
];

function MiniBarChart({ months, savings }) {
  const max = Math.max(...savings);
  return (
    <svg width="100%" height="120" viewBox={`0 0 ${months.length * 44} 120`} preserveAspectRatio="none">
      <defs>
        <linearGradient id="barGrad" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#0D9488"/>
          <stop offset="100%" stopColor="#14B8A6" stopOpacity="0.6"/>
        </linearGradient>
      </defs>
      {savings.map((v, i) => {
        const barH = Math.max(4, (v / max) * 90);
        const x = i * 44 + 4;
        const y = 96 - barH;
        return (
          <g key={i}>
            <rect x={x} y={y} width={36} height={barH} rx={4} fill="url(#barGrad)"/>
            <text x={x + 18} y={114} textAnchor="middle" fontSize="9" fill="#94A3B8">{months[i]}</text>
            <text x={x + 18} y={y - 3} textAnchor="middle" fontSize="8" fill="#0D9488" fontWeight="600">
              {v >= 1000 ? `${(v/1000).toFixed(0)}k` : v}
            </text>
          </g>
        );
      })}
    </svg>
  );
}

function ROIScreen({ user }) {
  const [period, setPeriod] = React.useState('6 Months');
  const d = periodData[period];

  // Real metrics from Supabase
  const [equipment, setEquipment]     = React.useState([]);
  const [calRecords, setCalRecords]   = React.useState([]);
  const [ppeInventory, setPPEInventory] = React.useState([]);
  const [issuances, setIssuances]     = React.useState([]);
  const [loading, setLoading]         = React.useState(true);

  React.useEffect(() => {
    if (!user) return;
    (async () => {
      try {
        const sb = window.supabaseClient;
        const [eq, cal, ppe, iss] = await Promise.all([
          sb.from('equipment').select('id,status,calibration_due'),
          sb.from('calibration_records').select('id,days_diff,has_issue,result,cal_date'),
          sb.from('ppe_inventory').select('id,status,balance,min_stock,stock,issued'),
          sb.from('ppe_issuance').select('id,qty,issued_at'),
        ]);
        setEquipment(eq.data || []);
        setCalRecords(cal.data || []);
        setPPEInventory(ppe.data || []);
        setIssuances(iss.data || []);
      } catch (err) {
        console.error('[ROI] load error:', err);
      } finally {
        setLoading(false);
      }
    })();
  }, [user]);

  const realMetrics = React.useMemo(() => {
    const eqTotal     = equipment.length;
    const eqCompliant = equipment.filter(e => e.status === 'active' || e.status === 'pending_calibration').length;
    const eqOverdue   = equipment.filter(e => e.status === 'overdue' || e.status === 'expired').length;
    const complianceScore = eqTotal > 0 ? Math.round((eqCompliant / eqTotal) * 100) : 0;

    const totalCals   = calRecords.length;
    const onTimeCals  = calRecords.filter(r => (r.days_diff || 0) <= 7).length;
    const onTimePct   = totalCals > 0 ? Math.round((onTimeCals / totalCals) * 100) : 0;
    const issuesCals  = calRecords.filter(r => r.has_issue).length;

    const totalUnits  = issuances.reduce((s, i) => s + (i.qty || 0), 0);
    const lowStock    = ppeInventory.filter(p => p.status === 'low' || p.status === 'critical').length;

    // Illustrative savings estimate (RM)
    // Penalty avoided = compliant calibrations × RM 500 estimated penalty per overdue cert
    const penaltyAvoided = onTimeCals * 500;
    // PPE wastage avoidance estimate = total issued × RM 8 saved per properly tracked unit
    const ppeSavings     = Math.round(totalUnits * 8);
    const totalSavings   = penaltyAvoided + ppeSavings;

    return { eqTotal, eqCompliant, eqOverdue, complianceScore, totalCals, onTimePct, issuesCals, totalUnits, lowStock, penaltyAvoided, ppeSavings, totalSavings };
  }, [equipment, calRecords, ppeInventory, issuances]);

  const handleExport = async () => {
    try {
      await window.AegisPDF.exportROIReport(user, realMetrics, period);
    } catch (err) {
      alert('PDF export failed: ' + err.message);
    }
  };

  return (
    <div style={roiStyles.page}>
      {/* Period + Export */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 20, flexWrap: 'wrap' }}>
        <span style={{ fontSize: 12, fontWeight: 600, color: '#64748B', marginRight: 4 }}>Period:</span>
        {PERIODS.map(p => (
          <button key={p} style={{ ...roiStyles.periodBtn, ...(period === p ? roiStyles.periodBtnActive : {}) }} onClick={() => setPeriod(p)}>{p}</button>
        ))}
        <div style={{ marginLeft: 'auto' }}>
          <button style={roiStyles.exportBtn} onClick={handleExport}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
            Export PDF Report
          </button>
        </div>
      </div>

      {/* AI Insight — live data */}
      <div style={roiStyles.insightBox}>
        <div style={roiStyles.insightIcon}>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#14B8A6" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>
        </div>
        <div>
          <div style={roiStyles.insightText}>
            Your current compliance score is <span style={{ color: '#14B8A6' }}>{realMetrics.complianceScore}%</span> across {realMetrics.eqTotal} pieces of equipment, with a <span style={{ color: '#14B8A6' }}>{realMetrics.onTimePct}%</span> on-time calibration rate.
          </div>
          <div style={roiStyles.insightSub}>
            {realMetrics.eqCompliant} compliant · {realMetrics.eqOverdue} overdue · {realMetrics.totalUnits} PPE units issued · est. RM {realMetrics.totalSavings.toLocaleString()} saved
          </div>
        </div>
      </div>

      {/* KPI row — first two are real, last two are illustrative */}
      <div style={roiStyles.topRow}>
        <div style={roiStyles.kpiCard}>
          <div style={roiStyles.kpiLabel}>Compliance Score (live)</div>
          <div style={{ ...roiStyles.kpiVal, color: realMetrics.complianceScore >= 85 ? '#16A34A' : realMetrics.complianceScore >= 60 ? '#D97706' : '#DC2626' }}>{realMetrics.complianceScore}%</div>
          <div style={{ ...roiStyles.kpiSub, color: '#64748B' }}>{realMetrics.eqCompliant} / {realMetrics.eqTotal} compliant equipment</div>
        </div>
        <div style={roiStyles.kpiCard}>
          <div style={roiStyles.kpiLabel}>On-Time Cal. Rate (live)</div>
          <div style={{ ...roiStyles.kpiVal, color: realMetrics.onTimePct >= 80 ? '#16A34A' : '#D97706' }}>{realMetrics.onTimePct}%</div>
          <div style={{ ...roiStyles.kpiSub, color: '#64748B' }}>{realMetrics.totalCals} total calibrations</div>
        </div>
        <div style={roiStyles.kpiCard}>
          <div style={roiStyles.kpiLabel}>Est. Penalties Avoided</div>
          <div style={{ ...roiStyles.kpiVal, color: '#0D9488' }}>RM {realMetrics.penaltyAvoided.toLocaleString()}</div>
          <div style={{ ...roiStyles.kpiSub, color: '#64748B' }}>RM 500 × {realMetrics.onTimePct > 0 ? 'on-time cals' : '—'}</div>
        </div>
        <div style={roiStyles.kpiCard}>
          <div style={roiStyles.kpiLabel}>Est. PPE Savings</div>
          <div style={{ ...roiStyles.kpiVal, color: '#16A34A' }}>RM {realMetrics.ppeSavings.toLocaleString()}</div>
          <div style={{ ...roiStyles.kpiSub, color: '#64748B' }}>~RM 8 per tracked issuance</div>
        </div>
      </div>

      <div style={{ background: '#FFFBEB', border: '1px solid #FDE68A', borderRadius: 6, padding: '10px 14px', fontSize: 12, color: '#92400E', marginBottom: 20, lineHeight: 1.6 }}>
        <strong>Note:</strong> The blue KPI cards (Compliance Score, On-Time Rate) reflect <strong>your real Supabase data</strong>. The penalty &amp; savings figures below are <strong>illustrative estimates</strong> based on industry averages — your actual savings depend on your baseline. The full Methodology note is at the bottom.
      </div>

      <div style={roiStyles.grid2}>
        {/* Monthly savings trend */}
        <div style={roiStyles.card}>
          <div style={roiStyles.cardTitle}>Monthly Savings Trend (RM)</div>
          <MiniBarChart months={d.months} savings={d.savings} />
        </div>

        {/* Before vs After */}
        <div style={roiStyles.card}>
          <div style={roiStyles.cardTitle}>Before vs After AegisComply</div>
          {compareMetrics.map((m, i) => {
            const max = Math.max(m.before, m.after);
            const beforePct = (m.before / max) * 100;
            const afterPct = (m.after / max) * 100;
            const higherBetter = m.higherIsBetter;
            return (
              <div key={i} style={{ marginBottom: 14 }}>
                <div style={{ fontSize: 11, fontWeight: 600, color: '#64748B', marginBottom: 5 }}>{m.label}</div>
                <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
                  <span style={{ fontSize: 10, color: '#94A3B8', minWidth: 36 }}>Before</span>
                  <div style={{ flex: 1, height: 18, background: '#F1F5F9', borderRadius: 4, overflow: 'hidden', position: 'relative' }}>
                    <div style={{ position: 'absolute', left: 0, top: 0, height: '100%', width: `${beforePct}%`, background: '#CBD5E1', borderRadius: 4, display: 'flex', alignItems: 'center', paddingLeft: 6 }}>
                      <span style={{ fontSize: 10, fontWeight: 700, color: '#475569', whiteSpace: 'nowrap' }}>{m.format(m.before)}</span>
                    </div>
                  </div>
                </div>
                <div style={{ display: 'flex', gap: 6, alignItems: 'center', marginTop: 4 }}>
                  <span style={{ fontSize: 10, color: '#94A3B8', minWidth: 36 }}>After</span>
                  <div style={{ flex: 1, height: 18, background: '#F1F5F9', borderRadius: 4, overflow: 'hidden', position: 'relative' }}>
                    <div style={{ position: 'absolute', left: 0, top: 0, height: '100%', width: `${Math.max(afterPct, 8)}%`, background: higherBetter ? '#0D9488' : '#14B8A6', borderRadius: 4, display: 'flex', alignItems: 'center', paddingLeft: 6 }}>
                      <span style={{ fontSize: 10, fontWeight: 700, color: 'white', whiteSpace: 'nowrap' }}>{m.format(m.after)}</span>
                    </div>
                  </div>
                  <span style={{ fontSize: 10, fontWeight: 700, color: '#16A34A', minWidth: 36 }}>
                    {higherBetter ? `+${Math.round(((m.after - m.before) / m.before) * 100)}%` : `−${Math.round(((m.before - m.after) / m.before) * 100)}%`}
                  </span>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Savings breakdown table */}
      <div style={roiStyles.tableCard}>
        <div style={{ padding: '13px 16px', borderBottom: '1px solid #F1F5F9', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <span style={{ fontFamily: "'Helvetica',sans-serif", fontSize: 14, fontWeight: 700, color: '#0F172A' }}>Savings Breakdown by Category</span>
          <span style={{ fontSize: 11, color: '#94A3B8' }}>All figures in Malaysian Ringgit (RM)</span>
        </div>
        <div style={roiStyles.thead}>
          {['Savings Category','Before System','After System','Annual Saving','Improvement'].map(h => <div key={h} style={roiStyles.thc}>{h}</div>)}
        </div>
        {savingsBreakdown.map((r, i) => (
          <div key={i} style={{ ...roiStyles.trow, background: i % 2 === 0 ? 'white' : '#FAFCFF' }}>
            <div style={{ fontSize: 13, fontWeight: 500, color: '#0F172A' }}>{r.category}</div>
            <div style={{ fontSize: 12, color: '#DC2626', fontWeight: 500 }}>{r.before}</div>
            <div style={{ fontSize: 12, color: '#16A34A', fontWeight: 500 }}>{r.after}</div>
            <div style={{ fontSize: 13, fontWeight: 700, color: '#0D9488' }}>RM {r.saved.toLocaleString()}</div>
            <div>
              <div style={{ height: 6, background: '#F0FDF4', borderRadius: 3, overflow: 'hidden', marginBottom: 3 }}>
                <div style={{ height: '100%', borderRadius: 3, background: '#16A34A', width: `${r.improvement}%` }}/>
              </div>
              <span style={{ fontSize: 11, fontWeight: 700, color: '#16A34A' }}>{r.improvement}%</span>
            </div>
          </div>
        ))}
        <div style={{ padding: '12px 16px', background: '#F0FDF4', borderTop: '2px solid #BBF7D0', display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1fr 100px', gap: 8 }}>
          <div style={{ fontSize: 13, fontWeight: 700, color: '#16A34A' }}>Total Annual Savings</div>
          <div></div><div></div>
          <div style={{ fontSize: 15, fontWeight: 800, color: '#16A34A', fontFamily: "'Helvetica',sans-serif" }}>RM {savingsBreakdown.reduce((s, r) => s + r.saved, 0).toLocaleString()}</div>
          <div></div>
        </div>
      </div>

      {/* Methodology note */}
      <div style={{ background: '#F8FAFC', border: '1px solid #E2E8F0', borderRadius: 8, padding: '14px 18px', fontSize: 12, color: '#64748B', lineHeight: 1.7 }}>
        <strong style={{ color: '#334155' }}>Methodology:</strong> Savings calculated based on company-provided baseline data entered during onboarding (manual tracking costs, historical penalty records, labour rates). Penalty avoidance figures reference DOSH Fine Schedule 2024. Downtime cost estimated at RM 1,200/day based on industry average for Malaysian process industries. All figures are estimates and should be verified against actual accounts.
      </div>
    </div>
  );
}

Object.assign(window, { ROIScreen });
