(function () {

const { useState: useStateRD, useEffect: useEffectRD } = React;

// Per-action enrichments — factors, forecast, predicted impact, summary
const ACTION_DETAILS = {
  1: {
    summary: "Three HVAC techs are out and a heat wave is going to push demand 35% above normal. You're 9 jobs over capacity. Reschedule Request can move non-urgent jobs to later in the week so your day-of emergencies still get served.",
    factors: [
      { label: "Weather forecast", value: "112°F highs Mon–Fri", source: "NOAA · Phoenix, AZ", weight: 0.32 },
      { label: "Tech availability", value: "4 of 7 HVAC techs (3 callouts)", source: "Dispatch board", weight: 0.28 },
      { label: "Confirmed appointments", value: "14 jobs Mon–Tue", source: "Schedule", weight: 0.18 },
      { label: "Historical heat-wave demand", value: "+35% on similar days", source: "Last 3 summers", weight: 0.14 },
      { label: "Customer urgency mix", value: "62% non-urgent maintenance", source: "Job tags last 30d", weight: 0.08 },
    ],
    forecast: { label: "HVAC demand — next 5 days", baseline: [22, 24, 23, 22, 21], predicted: [38, 41, 40, 36, 30], capacity: 32 },
    impact: {
      headline: "Prevents 9 missed appointments",
      metrics: [
        { label: "Same-day emergencies preserved", value: "100%", color: "#16a34a" },
        { label: "Non-urgent jobs rescheduled", value: "9", color: "#2563eb" },
        { label: "Estimated CSAT impact", value: "+0.3 pts", color: "#16a34a" },
        { label: "Risk of customer complaints", value: "Low", color: "#16a34a" },
      ],
      dollarImpact: "+$3,800 protected revenue",
    },
    risks: [
      "~2 of 9 rescheduled customers may push back; agent will offer priority scheduling later in the week.",
      "If demand exceeds forecast, additional automation may be needed mid-week.",
    ],
  },
  3: {
    summary: "$34,200 sits in invoices over 30 days late across 12 customers. AR Balance Collection has been disabled since the QuickBooks integration paused two weeks ago. Turning it back on starts SMS reminders within the hour and typically recovers 70%+ of aged AR within 14 days.",
    factors: [
      { label: "Aged AR balance", value: "$34,200 across 12 invoices", source: "QuickBooks AR aging", weight: 0.4 },
      { label: "Days past due (avg)", value: "47 days", source: "Invoice timestamps", weight: 0.22 },
      { label: "Automation status", value: "Disabled 14 days ago", source: "Automation log", weight: 0.18 },
      { label: "Historical recovery rate", value: "72% within 14 days", source: "Last 90d performance", weight: 0.14 },
      { label: "Customer dispute rate", value: "3% of attempts", source: "Last 6 months", weight: 0.06 },
    ],
    forecast: { label: "Projected AR recovery — 30 days", baseline: [0, 0, 0, 0, 0], predicted: [4500, 12000, 19500, 24600, 28800], capacity: 34200 },
    impact: {
      headline: "$24,000–$28,800 recoverable in 30 days",
      metrics: [
        { label: "Predicted recovery rate", value: "70–84%", color: "#16a34a" },
        { label: "Avg days to first response", value: "1.2 days", color: "#2563eb" },
        { label: "Customer churn risk", value: "Low", color: "#16a34a" },
        { label: "Manual effort saved", value: "~14 hrs/wk", color: "#16a34a" },
      ],
      dollarImpact: "+$24K–$28K recovered",
    },
    risks: [
      "3% of customers may dispute charges and require manual handling.",
      "Customers with valid payment plans should be excluded — agent will check before sending.",
    ],
  },
  4: {
    summary: "Phoenix Plumbing has 6 techs with open schedules and only 12 of 28 slots booked this week. Meanwhile, 34 unsold estimates from the last 60 days haven't been followed up. Deploying Unsold Estimates can fill ~8–12 slots from existing demand.",
    factors: [
      { label: "Stale estimates", value: "34 unsold > 14 days old", source: "Estimate database", weight: 0.36 },
      { label: "Open capacity this week", value: "16 of 28 slots open", source: "Plumbing schedule", weight: 0.24 },
      { label: "Estimate avg ticket", value: "$1,780", source: "Last 90d Plumbing", weight: 0.18 },
      { label: "Historical close rate (cold)", value: "26% with follow-up", source: "Plumbing 6mo data", weight: 0.14 },
      { label: "Customer recency", value: "Avg 32 days since estimate", source: "Estimate timestamps", weight: 0.08 },
    ],
    forecast: { label: "Plumbing slots booked — this week", baseline: [12, 13, 13, 14, 14, 14, 14], predicted: [12, 14, 17, 19, 21, 22, 22], capacity: 28 },
    impact: {
      headline: "Estimated +$14,200 recovered revenue",
      metrics: [
        { label: "Estimates re-engaged", value: "34", color: "#2563eb" },
        { label: "Predicted close rate", value: "24–28%", color: "#16a34a" },
        { label: "New booked jobs", value: "8–10", color: "#16a34a" },
        { label: "Slot utilization (this wk)", value: "45% → 78%", color: "#16a34a" },
      ],
      dollarImpact: "+$14,200 est. revenue",
    },
    risks: [
      "Estimates older than 60 days may have already gone with a competitor — exclude from first batch.",
      "Some customers may request a re-quote due to material price changes.",
    ],
  },
  5: {
    summary: "You're spending $400/day on Plumbing Google Ads but have capacity to handle roughly twice that volume. Conversion data shows headroom: cost-per-booked-job is $48 (well below the $90 target), and quality scores are healthy. Increasing the daily budget to $800 should bring +16 booked jobs this week.",
    factors: [
      { label: "Current daily spend", value: "$400/day", source: "Google Ads · Plumbing", weight: 0.3 },
      { label: "Cost per booked job", value: "$48 (target $90)", source: "GA + ST attribution", weight: 0.26 },
      { label: "Open Plumbing capacity", value: "16 slots/wk available", source: "Schedule", weight: 0.2 },
      { label: "Quality score (avg)", value: "8.4 / 10", source: "Google Ads", weight: 0.14 },
      { label: "Impression share lost (budget)", value: "47%", source: "Google Ads", weight: 0.1 },
    ],
    forecast: { label: "Plumbing booked jobs — next 7 days", baseline: [4, 4, 5, 4, 5, 4, 4], predicted: [6, 7, 8, 8, 9, 8, 8], capacity: 14 },
    impact: {
      headline: "+16 booked jobs this week",
      metrics: [
        { label: "Additional spend", value: "+$2,800/wk", color: "#d97706" },
        { label: "Predicted bookings", value: "+16", color: "#16a34a" },
        { label: "Predicted revenue", value: "+$28,500", color: "#16a34a" },
        { label: "Net margin impact", value: "+$8,900", color: "#16a34a" },
      ],
      dollarImpact: "+$8,900 net margin",
    },
    risks: [
      "Cost per click may rise as you bid more aggressively — agent will cap at $4.50 CPC.",
      "If competitors react, impression share gains may be temporary.",
    ],
  },
};

function ConfirmActivateModal({ open, onClose, action, onConfirm }) {
  useEffectRD(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  if (!open || !action) return null;
  const D = window.MAX_DATA;
  const { font, fg, muted, border, cardBg } = D;

  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "rgba(15,23,42,0.55)", backdropFilter: "blur(3px)", zIndex: 1000, display: "flex", alignItems: "center", justifyContent: "center", padding: 24 }}>
      <div onClick={e => e.stopPropagation()} style={{ background: cardBg, borderRadius: 14, width: "100%", maxWidth: 500, boxShadow: "0 30px 80px rgba(0,0,0,0.35)", overflow: "hidden", border: `1px solid ${border}` }}>
        <div style={{ padding: "20px 22px", borderBottom: `1px solid ${border}`, display: "flex", alignItems: "center", gap: 12 }}>
          <div style={{ background: "#dbeafe", borderRadius: 10, padding: 9, border: "1px solid #bfdbfe" }}><window.Icon name="Zap" size={18} color="#2563eb" /></div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 16, fontWeight: 800, color: fg, fontFamily: font, letterSpacing: -0.2 }}>Activate this automation?</div>
            <div style={{ fontSize: 11, color: muted, fontFamily: font, marginTop: 2 }}>Max will start running it immediately.</div>
          </div>
          <button onClick={onClose} style={{ background: "transparent", border: "none", cursor: "pointer", padding: 6, fontSize: 16, color: muted, fontFamily: font }}>✕</button>
        </div>

        <div style={{ padding: "20px 22px" }}>
          <div style={{ background: "#f8fafc", border: `1px solid ${border}`, borderRadius: 10, padding: "14px 16px", marginBottom: 16 }}>
            <div style={{ fontSize: 13, fontWeight: 800, color: fg, fontFamily: font, marginBottom: 6 }}>{action.rec}</div>
            <div style={{ fontSize: 12, color: muted, fontFamily: font, lineHeight: 1.5 }}>{action.desc}</div>
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 16 }}>
            <div style={{ background: "#f0fdf4", border: "1px solid #bbf7d0", borderRadius: 8, padding: "12px 14px" }}>
              <div style={{ fontSize: 9, fontWeight: 800, color: "#166534", fontFamily: font, textTransform: "uppercase", letterSpacing: 0.6, marginBottom: 4 }}>Expected impact</div>
              <div style={{ fontSize: 14, fontWeight: 800, color: "#16a34a", fontFamily: font }}>{action.impact}</div>
            </div>
            <div style={{ background: "#fffbeb", border: "1px solid #fde68a", borderRadius: 8, padding: "12px 14px" }}>
              <div style={{ fontSize: 9, fontWeight: 800, color: "#92400e", fontFamily: font, textTransform: "uppercase", letterSpacing: 0.6, marginBottom: 4 }}>Reversible</div>
              <div style={{ fontSize: 14, fontWeight: 800, color: "#d97706", fontFamily: font }}>Pause anytime</div>
            </div>
          </div>

          <div style={{ fontSize: 11, color: muted, fontFamily: font, lineHeight: 1.5, padding: "0 2px" }}>
            <window.Icon name="Info" size={11} /> Max will notify you within 24 hours with results. You can review or pause this in <strong>What Max Did</strong>.
          </div>
        </div>

        <div style={{ padding: "12px 22px", borderTop: `1px solid ${border}`, display: "flex", justifyContent: "flex-end", gap: 8, background: "#fafbfc" }}>
          <button onClick={onClose} style={{ padding: "8px 16px", borderRadius: 8, background: "transparent", color: fg, border: `1px solid ${border}`, cursor: "pointer", fontSize: 12, fontWeight: 700, fontFamily: font }}>Cancel</button>
          <button onClick={() => { onConfirm(action); onClose(); }} style={{ padding: "8px 18px", borderRadius: 8, background: "#2563eb", color: "white", border: "none", cursor: "pointer", fontSize: 12, fontWeight: 700, fontFamily: font, display: "flex", alignItems: "center", gap: 6 }}>
            <window.Icon name="Check" size={13} color="white" /> Activate
          </button>
        </div>
      </div>
    </div>
  );
}

function DetailsModal({ open, onClose, action, onActivate }) {
  useEffectRD(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  if (!open || !action) return null;
  const D = window.MAX_DATA;
  const { font, fg, muted, border, cardBg } = D;
  const details = ACTION_DETAILS[action.id] || ACTION_DETAILS[1];

  // Build forecast chart points
  const fc = details.forecast;
  const days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].slice(0, fc.predicted.length);
  const maxY = Math.max(...fc.predicted, ...fc.baseline, fc.capacity) * 1.1;

  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "rgba(15,23,42,0.6)", backdropFilter: "blur(3px)", zIndex: 1000, display: "flex", alignItems: "center", justifyContent: "center", padding: 24 }}>
      <div onClick={e => e.stopPropagation()} style={{ background: cardBg, borderRadius: 14, width: "100%", maxWidth: 880, maxHeight: "92vh", display: "flex", flexDirection: "column", boxShadow: "0 30px 80px rgba(0,0,0,0.4)", overflow: "hidden", border: `1px solid ${border}` }}>
        {/* Header — dark like Daily Brief */}
        <div style={{ padding: "20px 26px", background: "linear-gradient(135deg, #0f1f3d 0%, #141414 100%)", display: "flex", alignItems: "flex-start", gap: 14, position: "relative", overflow: "hidden" }}>
          <div style={{ position: "absolute", top: -40, right: -40, width: 200, height: 200, borderRadius: "50%", background: "rgba(120,187,250,0.06)", filter: "blur(20px)" }} />
          <div style={{ background: "rgba(120,187,250,0.15)", borderRadius: 10, padding: 10, border: "1px solid rgba(120,187,250,0.25)", flexShrink: 0, position: "relative" }}><window.Icon name="Sparkles" size={18} color="#78bbfa" /></div>
          <div style={{ flex: 1, position: "relative", minWidth: 0 }}>
            <div style={{ fontSize: 10, color: "rgba(255,255,255,0.45)", fontFamily: font, fontWeight: 700, textTransform: "uppercase", letterSpacing: 0.8, marginBottom: 4 }}>Why Max recommends this</div>
            <div style={{ fontSize: 18, fontWeight: 800, color: "white", fontFamily: font, letterSpacing: -0.3, lineHeight: 1.3, marginBottom: 6 }}>{action.rec}</div>
            <div style={{ fontSize: 12, color: "rgba(255,255,255,0.7)", fontFamily: font, lineHeight: 1.55 }}>{details.summary}</div>
          </div>
          <button onClick={onClose} style={{ background: "rgba(255,255,255,0.08)", border: "1px solid rgba(255,255,255,0.15)", cursor: "pointer", padding: "4px 10px", fontSize: 14, color: "rgba(255,255,255,0.7)", fontFamily: font, borderRadius: 6, position: "relative", flexShrink: 0 }}>✕</button>
        </div>

        {/* Body */}
        <div style={{ flex: 1, overflowY: "auto", padding: "22px 26px", background: "#fafbfc" }}>

          {/* Predicted impact */}
          <div style={{ marginBottom: 22 }}>
            <SectionHeader icon="TrendingUp" color="#16a34a" title="Predicted impact" sub={details.impact.headline} />
            <div style={{ background: cardBg, border: `1px solid ${border}`, borderRadius: 10, padding: "16px 18px" }}>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12, marginBottom: 14 }}>
                {details.impact.metrics.map((m, i) => (
                  <div key={i}>
                    <div style={{ fontSize: 10, fontWeight: 700, color: muted, fontFamily: font, textTransform: "uppercase", letterSpacing: 0.5, marginBottom: 4 }}>{m.label}</div>
                    <div style={{ fontSize: 18, fontWeight: 800, color: m.color, fontFamily: font, letterSpacing: -0.3, lineHeight: 1 }}>{m.value}</div>
                  </div>
                ))}
              </div>
              <div style={{ borderTop: `1px solid ${border}`, paddingTop: 12, display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                <span style={{ fontSize: 11, color: muted, fontFamily: font }}>Bottom-line</span>
                <span style={{ fontSize: 16, fontWeight: 800, color: "#16a34a", fontFamily: font }}>{details.impact.dollarImpact}</span>
              </div>
            </div>
          </div>

          {/* Demand forecast */}
          <div style={{ marginBottom: 22 }}>
            <SectionHeader icon="LineChart" color="#2563eb" title="Forecast" sub={fc.label} />
            <div style={{ background: cardBg, border: `1px solid ${border}`, borderRadius: 10, padding: "16px 18px" }}>
              <ForecastChart days={days} baseline={fc.baseline} predicted={fc.predicted} capacity={fc.capacity} maxY={maxY} font={font} muted={muted} fg={fg} />
              <div style={{ display: "flex", gap: 16, marginTop: 12, fontSize: 11, fontFamily: font, color: muted, flexWrap: "wrap" }}>
                <Legend color="#cbd5e1" label="Baseline (no action)" />
                <Legend color="#2563eb" label="Predicted (with action)" />
                <Legend color="#dc2626" label="Capacity ceiling" dashed />
              </div>
            </div>
          </div>

          {/* Factors */}
          <div style={{ marginBottom: 22 }}>
            <SectionHeader icon="Layers" color="#7c3aed" title="Factors that drove this" sub={`${details.factors.length} signals weighted by recency, confidence, and impact`} />
            <div style={{ background: cardBg, border: `1px solid ${border}`, borderRadius: 10, overflow: "hidden" }}>
              {details.factors.map((f, i) => (
                <div key={i} style={{ display: "grid", gridTemplateColumns: "1fr 1fr 100px 80px", gap: 14, alignItems: "center", padding: "12px 16px", borderBottom: i === details.factors.length - 1 ? "none" : `1px solid ${border}`, fontFamily: font }}>
                  <div>
                    <div style={{ fontSize: 12, fontWeight: 700, color: fg }}>{f.label}</div>
                    <div style={{ fontSize: 10, color: muted, marginTop: 2 }}>{f.source}</div>
                  </div>
                  <div style={{ fontSize: 12, fontWeight: 600, color: fg }}>{f.value}</div>
                  <div>
                    <div style={{ height: 6, background: "#f1f5f9", borderRadius: 99, overflow: "hidden" }}>
                      <div style={{ width: `${f.weight * 100}%`, height: "100%", background: "linear-gradient(90deg, #7c3aed, #a855f7)", borderRadius: 99 }} />
                    </div>
                  </div>
                  <div style={{ fontSize: 11, fontWeight: 700, color: fg, textAlign: "right" }}>{Math.round(f.weight * 100)}%</div>
                </div>
              ))}
            </div>
          </div>

          {/* Risks */}
          <div>
            <SectionHeader icon="AlertTriangle" color="#d97706" title="Risks & considerations" sub="Max accounts for these automatically" />
            <div style={{ background: "#fffbeb", border: "1px solid #fde68a", borderRadius: 10, padding: "12px 16px" }}>
              {details.risks.map((r, i) => (
                <div key={i} style={{ display: "flex", gap: 10, padding: "6px 0", fontFamily: font, fontSize: 12, color: "#78350f", lineHeight: 1.55 }}>
                  <span style={{ color: "#d97706", flexShrink: 0 }}>•</span>
                  <span>{r}</span>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Footer */}
        <div style={{ padding: "14px 26px", borderTop: `1px solid ${border}`, display: "flex", alignItems: "center", justifyContent: "space-between", background: cardBg }}>
          <span style={{ fontSize: 11, color: muted, fontFamily: font }}>
            <window.Icon name="Sparkles" size={11} /> Generated {new Date().toLocaleTimeString([], { hour: "numeric", minute: "2-digit" })} · Confidence: <strong style={{ color: "#16a34a" }}>High (87%)</strong>
          </span>
          <div style={{ display: "flex", gap: 8 }}>
            <button onClick={onClose} style={{ padding: "8px 16px", borderRadius: 8, background: "transparent", color: fg, border: `1px solid ${border}`, cursor: "pointer", fontSize: 12, fontWeight: 700, fontFamily: font }}>Close</button>
            <button onClick={() => { onClose(); onActivate(action); }} style={{ padding: "8px 18px", borderRadius: 8, background: "#2563eb", color: "white", border: "none", cursor: "pointer", fontSize: 12, fontWeight: 700, fontFamily: font, display: "flex", alignItems: "center", gap: 6 }}>
              <window.Icon name="Zap" size={13} color="white" /> Activate
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

function SectionHeader({ icon, color, title, sub }) {
  const { font, fg, muted } = window.MAX_DATA;
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 10 }}>
      <div style={{ background: `${color}15`, borderRadius: 7, padding: 6, border: `1px solid ${color}30` }}><window.Icon name={icon} size={13} color={color} /></div>
      <div>
        <div style={{ fontSize: 13, fontWeight: 800, color: fg, fontFamily: font }}>{title}</div>
        <div style={{ fontSize: 11, color: muted, fontFamily: font }}>{sub}</div>
      </div>
    </div>
  );
}

function Legend({ color, label, dashed }) {
  const { font } = window.MAX_DATA;
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 6, fontFamily: font }}>
      <span style={{ width: 22, height: 2, background: dashed ? "transparent" : color, borderTop: dashed ? `2px dashed ${color}` : "none" }} />
      {label}
    </div>
  );
}

function ForecastChart({ days, baseline, predicted, capacity, maxY, font, muted, fg }) {
  const W = 740, H = 180, padX = 36, padY = 20;
  const innerW = W - padX * 2, innerH = H - padY * 2;
  const xStep = days.length > 1 ? innerW / (days.length - 1) : 0;
  const y = v => padY + innerH - (v / maxY) * innerH;
  const xPos = i => padX + i * xStep;

  const baselinePath = baseline.map((v, i) => `${i === 0 ? "M" : "L"}${xPos(i)},${y(v)}`).join(" ");
  const predictedPath = predicted.map((v, i) => `${i === 0 ? "M" : "L"}${xPos(i)},${y(v)}`).join(" ");
  const predictedArea = `${predictedPath} L${xPos(days.length - 1)},${y(0)} L${xPos(0)},${y(0)} Z`;

  const yTicks = [0, Math.round(maxY * 0.5), Math.round(maxY)];

  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{ width: "100%", height: 180, fontFamily: font }}>
      <defs>
        <linearGradient id="predFill" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#2563eb" stopOpacity="0.25" />
          <stop offset="100%" stopColor="#2563eb" stopOpacity="0" />
        </linearGradient>
      </defs>
      {/* gridlines */}
      {yTicks.map((t, i) => (
        <g key={i}>
          <line x1={padX} x2={W - padX} y1={y(t)} y2={y(t)} stroke="#e5e7eb" strokeWidth="1" />
          <text x={padX - 6} y={y(t) + 4} textAnchor="end" fontSize="10" fill={muted}>{t}</text>
        </g>
      ))}
      {/* Capacity ceiling */}
      <line x1={padX} x2={W - padX} y1={y(capacity)} y2={y(capacity)} stroke="#dc2626" strokeWidth="1.5" strokeDasharray="5,4" />
      <text x={W - padX} y={y(capacity) - 5} textAnchor="end" fontSize="10" fill="#dc2626" fontWeight="700">Capacity {capacity}</text>
      {/* Predicted area + line */}
      <path d={predictedArea} fill="url(#predFill)" />
      <path d={predictedPath} fill="none" stroke="#2563eb" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
      {predicted.map((v, i) => (
        <circle key={i} cx={xPos(i)} cy={y(v)} r="3.5" fill="#2563eb" stroke="white" strokeWidth="1.5" />
      ))}
      {/* Baseline (lighter) */}
      <path d={baselinePath} fill="none" stroke="#cbd5e1" strokeWidth="2" strokeDasharray="3,3" />
      {/* X axis labels */}
      {days.map((d, i) => (
        <text key={i} x={xPos(i)} y={H - 4} textAnchor="middle" fontSize="10" fill={muted} fontWeight="600">{d}</text>
      ))}
    </svg>
  );
}

window.ConfirmActivateModal = ConfirmActivateModal;
window.DetailsModal = DetailsModal;
window.ACTION_DETAILS = ACTION_DETAILS;

})();
