// Max Home page
(function () {

const { useState: useStateMH } = React;
const {
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer,
  ReferenceLine, ComposedChart, Line, Area
} = window.Recharts;

function MaxHomePage() {
  const D = window.MAX_DATA;
  const { font, fg, muted, border, cardBg, recommendedActions, capacityData, conversionData, workflows } = D;
  const [autoOptimizerEnabled, setAutoOptimizerEnabled] = useStateMH(true);
  const [actionsVisible, setActionsVisible] = useStateMH([1, 3, 4, 5]);
  const [showAllActions] = useStateMH(false);
  const [workflowToggles, setWorkflowToggles] = useStateMH({ "speed-to-lead": true, "unsold-estimates": true, "reschedule-request": true, "aging-equipment": false, "memberships": true, "pre-appt-nurture": true });
  const [strategyOpen, setStrategyOpen] = useStateMH(false);
  const [strategy, setStrategy] = useStateMH(window.DEFAULT_STRATEGY);
  const [strategyToast, setStrategyToast] = useStateMH(null);
  const [confirmAction, setConfirmAction] = useStateMH(null);
  const [detailsAction, setDetailsAction] = useStateMH(null);
  const [activatedToast, setActivatedToast] = useStateMH(null);

  const activateAction = (action) => {
    setActionsVisible(v => v.filter(id => id !== action.id));
    setActivatedToast(action);
    setTimeout(() => setActivatedToast(null), 3500);
  };

  const severityBorder = { critical: "#fca5a5", warning: "#fcd34d", info: "#93c5fd" };

  return (
    <div style={{ padding: "24px 28px", maxWidth: 1300, margin: "0 auto" }}>
      {/* Header */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 16 }}>
        <div>
          <h1 style={{ fontSize: 24, fontWeight: 700, color: fg, fontFamily: font, margin: 0 }}>Max</h1>
          <p style={{ fontSize: 13, color: muted, fontFamily: font, marginTop: 2 }}>AI-powered insights and automations across your business</p>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <button style={{ display: "flex", alignItems: "center", gap: 6, border: `1px solid ${border}`, background: cardBg, padding: "7px 14px", borderRadius: 8, cursor: "pointer", fontSize: 12, fontFamily: font, fontWeight: 600, color: fg }}><window.Icon name="History" size={14} /> View History</button>
          <button onClick={() => setStrategyOpen(true)} style={{ display: "flex", alignItems: "center", gap: 6, border: "1px solid #2563eb", background: "#eff6ff", padding: "7px 14px", borderRadius: 8, cursor: "pointer", fontSize: 12, fontFamily: font, fontWeight: 600, color: "#2563eb" }}><window.Icon name="Settings" size={14} color="#2563eb" /> Configure Strategy</button>
        </div>
      </div>

      {/* REVENUE EQUATION — page-level lens */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr auto 1fr auto 1fr auto 1.2fr", alignItems: "stretch", background: cardBg, border: `1px solid ${border}`, borderRadius: 12, marginBottom: 16, overflow: "hidden" }}>
        {[
          { label: "Leads Generated", value: "1,247", trend: "+12%", sub: "vs last 30 days", current: 1247, benchmark: 1050, benchmarkDisplay: "1,050/mo", gap: "+197 leads", above: true },
          { label: "Booking Rate", value: "68%", trend: "+3 pts", sub: "of leads booked", current: 68, benchmark: 78, benchmarkDisplay: "78%", gap: "-10 pts", above: false },
          { label: "Avg Ticket", value: "$4,280", trend: "+5%", sub: "per completed job", current: 4280, benchmark: 5800, benchmarkDisplay: "$5,800", gap: "-$1,520", above: false },
          { label: "Revenue", value: "$284.6K", trend: "+14%", sub: "last 30 days", final: true, current: 284600, benchmark: 350000, benchmarkDisplay: "$350K", gap: "-$65.4K", above: false },
        ].map((m, i, arr) => {
          const ratio = m.current / m.benchmark;
          const barColor = ratio >= 1 ? "#16a34a" : ratio >= 0.85 ? "#f59e0b" : "#ef4444";
          const gapColor = m.above ? "#16a34a" : ratio >= 0.85 ? "#f59e0b" : "#ef4444";
          const maxBar = m.benchmark * 1.2;
          const fillPct = Math.min((m.current / maxBar) * 100, 100);
          const markerPct = (m.benchmark / maxBar) * 100;
          return (
          <React.Fragment key={i}>
            <div style={{ padding: "14px 18px", background: m.final ? "linear-gradient(135deg, rgba(22,163,74,0.06), rgba(22,163,74,0.02))" : "transparent", display: "flex", flexDirection: "column", justifyContent: "center" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 4 }}>
                <span style={{ fontSize: 9, color: muted, fontFamily: font, fontWeight: 700, textTransform: "uppercase", letterSpacing: 0.6 }}>{m.label}</span>
                <span style={{ fontSize: 9, fontWeight: 700, color: "#16a34a", background: "#dcfce7", padding: "1px 6px", borderRadius: 99, fontFamily: font }}>↑ {m.trend}</span>
              </div>
              <div style={{ fontSize: 26, fontWeight: 800, color: m.final ? "#16a34a" : fg, fontFamily: font, lineHeight: 1, letterSpacing: -0.5 }}>{m.value}</div>
              <div style={{ fontSize: 10, color: muted, fontFamily: font, marginTop: 4, marginBottom: 10 }}>{m.sub}</div>
              {/* Benchmark progress bar */}
              <div style={{ position: "relative", height: 5, background: "#f0f0f0", borderRadius: 99, marginBottom: 6 }}>
                <div style={{ position: "absolute", left: 0, top: 0, width: `${fillPct}%`, height: "100%", background: barColor, borderRadius: 99, opacity: 0.8 }} />
                <div style={{ position: "absolute", top: -3, left: `${markerPct}%`, transform: "translateX(-50%)", width: 2, height: 11, background: "#374151", borderRadius: 1, opacity: 0.5 }} />
              </div>
              {/* Benchmark label */}
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                <span style={{ fontSize: 9, color: muted, fontFamily: font }}>Top performers: <strong style={{ color: "#374151" }}>{m.benchmarkDisplay}</strong></span>
                <span style={{ fontSize: 9, fontWeight: 700, color: gapColor, fontFamily: font }}>{m.gap}</span>
              </div>
            </div>
            {i < arr.length - 1 && (
              <div style={{ display: "flex", alignItems: "center", justifyContent: "center", padding: "0 4px", color: "#cbd5e1", fontSize: 22, fontWeight: 300, fontFamily: font, userSelect: "none" }}>
                {i === arr.length - 2 ? "=" : "×"}
              </div>
            )}
          </React.Fragment>
          );
        })}
      </div>

      {/* DAILY BRIEF */}
      <div style={{ background: "linear-gradient(135deg, #0f1f3d 0%, #141414 100%)", borderRadius: 12, padding: "22px 24px 20px", marginBottom: 16, 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={{ position: "absolute", bottom: -50, left: 100, width: 140, height: 140, borderRadius: "50%", background: "rgba(37,99,235,0.05)", filter: "blur(20px)" }} />

        <div style={{ position: "relative" }}>
          <div style={{ display: "flex", alignItems: "flex-end", gap: 12, marginBottom: 18, paddingBottom: 16, borderBottom: "1px solid rgba(255,255,255,0.08)" }}>
            <div style={{ background: "rgba(120,187,250,0.15)", borderRadius: 10, padding: 10, border: "1px solid rgba(120,187,250,0.25)" }}><window.Icon name="Sparkles" size={20} color="#78bbfa" /></div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 10, color: "rgba(255,255,255,0.4)", fontFamily: font, fontWeight: 700, textTransform: "uppercase", letterSpacing: 0.8, marginBottom: 2 }}>Monday Brief · Apr 28, 7:00 AM</div>
              <div style={{ fontSize: 22, fontWeight: 800, color: "white", fontFamily: font, letterSpacing: -0.4, lineHeight: 1.15 }}>
                Good morning. Three things need a decision today.
              </div>
            </div>
            <span style={{ fontSize: 10, color: "rgba(255,255,255,0.4)", fontFamily: font, fontWeight: 600, paddingBottom: 2 }}>{actionsVisible.length} pending · ~6 min read</span>
          </div>

          {/* Narrative situations */}
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            {[
              { num: "01", chip: "Critical", chipColor: "#fca5a5", accent: "#ef4444",
                lede: "Scottsdale heat wave + 3 techs out — you're 9 jobs over capacity.",
                briefText: "112°F highs Monday through Friday will spike HVAC demand by ~35%. With 3 technicians called out, you have 14 confirmed appointments and 4 techs available. Reschedule Request can move non-urgent jobs to later in the week and protect your same-day emergencies.",
                actionIds: [1] },
              { num: "02", chip: "Warning", chipColor: "#fcd34d", accent: "#f59e0b",
                lede: "$34,200 in receivables sitting past due, and collection is off.",
                briefText: "12 invoices over 30 days late. AR Balance Collection has been disabled since the integration was paused two weeks ago. Turning it back on starts SMS reminders within the hour.",
                actionIds: [3] },
              { num: "03", chip: "Opportunity", chipColor: "#93c5fd", accent: "#3b82f6",
                lede: "Phoenix Plumbing at 45% capacity — 6 techs idle, 34 stale estimates.",
                briefText: "Only 12 of 28 slots are booked this week. Meanwhile, 34 unsold estimates from the last 60 days haven't had a follow-up, and Google Ads spend for Plumbing is conservatively set at $400/day. There's runway here.",
                actionIds: [4, 5] },
            ].map((section, si) => {
              const sectionActions = recommendedActions.filter(a => section.actionIds.includes(a.id) && actionsVisible.includes(a.id));
              const allDismissed = sectionActions.length === 0;
              if (allDismissed && !showAllActions) {
                return (
                  <div key={si} style={{ display: "flex", gap: 14, opacity: 0.45 }}>
                    <div style={{ width: 3, background: section.accent, borderRadius: 2, flexShrink: 0 }} />
                    <div style={{ flex: 1, paddingTop: 2 }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 12, color: "rgba(255,255,255,0.6)", fontFamily: font, fontWeight: 600 }}>
                        <span>{section.num}</span>
                        <span style={{ textDecoration: "line-through" }}>{section.lede}</span>
                        <span style={{ fontSize: 10, color: "#4ade80", fontWeight: 700 }}>✓ Addressed</span>
                      </div>
                    </div>
                  </div>
                );
              }
              return (
                <div key={si} style={{ display: "flex", gap: 14 }}>
                  {/* Severity rail */}
                  <div style={{ width: 3, background: section.accent, borderRadius: 2, flexShrink: 0, opacity: 0.85 }} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    {/* Header row: number + chip + lede */}
                    <div style={{ display: "flex", alignItems: "baseline", gap: 10, marginBottom: 6, flexWrap: "wrap" }}>
                      <span style={{ fontSize: 11, color: "rgba(255,255,255,0.35)", fontFamily: font, fontWeight: 700, letterSpacing: 0.5 }}>{section.num}</span>
                      <span style={{ fontSize: 9, fontWeight: 800, color: section.chipColor, background: `${section.accent}22`, border: `1px solid ${section.accent}55`, padding: "2px 8px", borderRadius: 99, textTransform: "uppercase", letterSpacing: 0.6, fontFamily: font }}>{section.chip}</span>
                      <span style={{ fontSize: 14, fontWeight: 700, color: "white", fontFamily: font, lineHeight: 1.3 }}>{section.lede}</span>
                    </div>
                    {/* Briefing paragraph */}
                    <p style={{ fontSize: 12.5, color: "rgba(255,255,255,0.7)", fontFamily: font, lineHeight: 1.6, margin: "0 0 10px 0" }}>{section.briefText}</p>
                    {/* Actions */}
                    <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                      {sectionActions.map(action => (
                        <div key={action.id} style={{ background: "rgba(255,255,255,0.04)", borderRadius: 8, border: "1px solid rgba(255,255,255,0.08)", display: "flex", alignItems: "center", padding: "10px 14px", gap: 12, transition: "background 0.15s" }}
                          onMouseEnter={e => e.currentTarget.style.background = "rgba(255,255,255,0.07)"}
                          onMouseLeave={e => e.currentTarget.style.background = "rgba(255,255,255,0.04)"}>
                          <window.Icon name="ArrowRight" size={13} color="rgba(255,255,255,0.4)" style={{ flexShrink: 0 }} />
                          <div style={{ flex: 1, minWidth: 0 }}>
                            <div style={{ fontSize: 12, fontWeight: 700, color: "white", fontFamily: font, marginBottom: 2 }}>{action.rec}</div>
                            <div style={{ fontSize: 10, color: "#4ade80", fontFamily: font, fontWeight: 600 }}>{action.impact}</div>
                          </div>
                          <div style={{ display: "flex", alignItems: "center", gap: 4, flexShrink: 0 }}>
                            <button onClick={() => setConfirmAction(action)} style={{ padding: "5px 14px", borderRadius: 6, background: "#2563eb", color: "white", border: "none", cursor: "pointer", fontSize: 11, fontWeight: 700, fontFamily: font }}>Activate</button>
                            <button onClick={() => setDetailsAction(action)} style={{ padding: "5px 10px", borderRadius: 6, background: "transparent", color: "rgba(255,255,255,0.7)", border: "1px solid rgba(255,255,255,0.12)", cursor: "pointer", fontSize: 11, fontWeight: 600, fontFamily: font }}>Details</button>
                            <button onClick={() => setActionsVisible(v => v.filter(id => id !== action.id))} title="Dismiss" style={{ padding: "5px 8px", background: "none", border: "none", cursor: "pointer", fontSize: 13, color: "rgba(255,255,255,0.3)", fontFamily: font, lineHeight: 1 }}>✕</button>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>

          {actionsVisible.length === 0 && (
            <div style={{ textAlign: "center", padding: "20px 0 4px", marginTop: 8, borderTop: "1px solid rgba(255,255,255,0.08)" }}>
              <div style={{ fontSize: 26, marginBottom: 4 }}>☕</div>
              <p style={{ fontSize: 14, fontWeight: 700, color: "white", fontFamily: font, margin: 0 }}>All caught up — see you tomorrow.</p>
              <p style={{ fontSize: 11, color: "rgba(255,255,255,0.5)", fontFamily: font, marginTop: 4 }}>Max is monitoring your business and will alert you when something needs attention.</p>
            </div>
          )}
        </div>
      </div>

      {/* WHAT MAX DID */}
      <div style={{ background: "linear-gradient(135deg, #0f1f3d 0%, #141414 100%)", borderRadius: 12, padding: "20px 22px", marginBottom: 16, position: "relative", overflow: "hidden" }}>
        <div style={{ position: "absolute", top: -40, right: -40, width: 200, height: 200, borderRadius: "50%", background: "rgba(34,197,94,0.05)", filter: "blur(20px)" }} />
        <div style={{ position: "relative" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 16 }}>
            <div style={{ background: "rgba(34,197,94,0.15)", borderRadius: 10, padding: 10, border: "1px solid rgba(74,222,128,0.25)" }}><window.Icon name="Zap" size={18} color="#4ade80" /></div>
            <div>
              <div style={{ fontSize: 10, color: "rgba(255,255,255,0.4)", fontFamily: font, fontWeight: 700, textTransform: "uppercase", letterSpacing: 0.8, marginBottom: 2 }}>Auto-Optimizer · Last 48 hours</div>
              <span style={{ fontSize: 22, fontWeight: 800, color: "white", fontFamily: font, letterSpacing: -0.4 }}>What Max Did</span>
            </div>
            <div style={{ marginLeft: "auto", textAlign: "right" }}>
              <span style={{ fontSize: 16, fontWeight: 800, color: "#4ade80", fontFamily: font }}>+$4,200</span>
              <span style={{ fontSize: 10, color: "rgba(255,255,255,0.4)", fontFamily: font, display: "block" }}>estimated impact</span>
            </div>
          </div>

          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {[
              { brief: "Max noticed that Unsold Estimate follow-ups sent at 3 PM had a 12% response rate, but similar messages sent at 6 PM in a prior test hit 20%. It shifted all Plumbing follow-ups to 6 PM on Tuesday.",
                title: "Shifted Unsold Estimates timing to 6 PM",
                result: "Result: response rate up from 12% → 19%", resultColor: "#4ade80",
                meta: "· 3 additional estimates recovered ($2,400)", strong: true },
              { brief: "The Speed-to-Lead AI agent was using a formal tone for Angi leads, but Angi customers respond better to casual, friendly language. Max switched the agent's tone to \"Friendly\" for all Angi-sourced leads on Wednesday.",
                title: "Updated Speed-to-Lead tone to \"Friendly\" for Angi leads",
                result: "Result: booking rate up from 38% → 44%", resultColor: "#4ade80",
                meta: "· 5 additional bookings ($1,800)", strong: true },
              { brief: "The Reschedule Request automation was only making 2 follow-up attempts before giving up. Data showed a 3rd attempt converts an additional 5% of customers. Max increased attempts to 3 yesterday.",
                title: "Increased Reschedule Request follow-ups from 2 → 3",
                result: "Measuring: too early for results", resultColor: "#fbbf24",
                meta: "· predicted +5% booking rate", strong: false },
            ].map((c, i) => (
              <div key={i}>
                <p style={{ fontSize: 12, color: "rgba(255,255,255,0.7)", fontFamily: font, lineHeight: 1.5, marginBottom: 8, paddingLeft: 2 }}>{c.brief}</p>
                <div style={{ background: "rgba(255,255,255,0.06)", borderRadius: 8, border: c.strong ? "1px solid rgba(74,222,128,0.2)" : "1px solid rgba(74,222,128,0.15)", borderLeft: c.strong ? "3px solid #4ade80" : "3px solid rgba(74,222,128,0.4)", padding: "8px 12px", display: "flex", alignItems: "center", gap: 10 }}>
                  <div style={{ flex: 1 }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                      <span style={{ fontSize: 11, fontWeight: 700, color: "white", fontFamily: font }}>{c.title}</span>
                    </div>
                    <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 3 }}>
                      <span style={{ fontSize: 10, color: c.resultColor, fontFamily: font, fontWeight: 700 }}>{c.result}</span>
                      <span style={{ fontSize: 10, color: "rgba(255,255,255,0.4)", fontFamily: font }}>{c.meta}</span>
                    </div>
                  </div>
                  <div style={{ display: "flex", alignItems: "center", gap: 4, flexShrink: 0 }}>
                    <button style={{ padding: "4px 10px", borderRadius: 5, background: "rgba(255,255,255,0.08)", color: "rgba(255,255,255,0.7)", border: "1px solid rgba(255,255,255,0.12)", cursor: "pointer", fontSize: 10, fontWeight: 600, fontFamily: font }}>Details</button>
                    <button style={{ display: "flex", alignItems: "center", gap: 3, padding: "4px 10px", borderRadius: 5, background: "rgba(255,255,255,0.05)", color: "rgba(255,255,255,0.5)", border: "1px solid rgba(255,255,255,0.08)", cursor: "pointer", fontSize: 10, fontWeight: 600, fontFamily: font }}><window.Icon name="RotateCcw" size={9} color="rgba(255,255,255,0.5)" /> Revert</button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* CAPACITY UTILIZATION */}
      <div style={{ background: cardBg, borderRadius: 10, border: `1px solid ${border}`, overflow: "hidden", marginBottom: 16 }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "12px 20px", borderBottom: `1px solid ${border}` }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <window.Icon name="BarChart3" size={16} color="#2563eb" />
            <span style={{ fontSize: 14, fontWeight: 700, color: fg, fontFamily: font }}>Capacity Utilization %</span>
            <span style={{ fontSize: 11, color: muted, fontFamily: font }}>— 10-day forecast</span>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 4 }}>
                <div style={{ width: 10, height: 10, borderRadius: 2, background: "#2563eb", opacity: 0.5 }} />
                <span style={{ fontSize: 10, color: muted, fontFamily: font }}>Predicted</span>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 4 }}>
                <div style={{ width: 10, height: 10, borderRadius: 2, background: "#6B7280" }} />
                <span style={{ fontSize: 10, color: muted, fontFamily: font }}>Actual</span>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 4 }}>
                <div style={{ width: 16, height: 0, borderTop: "2px dashed #6B7280" }} />
                <span style={{ fontSize: 10, color: muted, fontFamily: font }}>100% target</span>
              </div>
            </div>
          </div>
        </div>
        <div style={{ padding: "12px 12px 4px 0" }}>
          <ResponsiveContainer width="100%" height={200}>
            <BarChart data={capacityData} barGap={6} barCategoryGap="15%" margin={{ top: 8, right: 12, bottom: 0, left: 4 }}>
              <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" vertical={false} />
              <XAxis dataKey="date" tick={{ fill: muted, fontSize: 11, fontFamily: font }} stroke="transparent" tickLine={false} dy={4} />
              <YAxis tick={{ fill: muted, fontSize: 10, fontFamily: font }} stroke="transparent" tickLine={false} axisLine={false} domain={[0, 150]} ticks={[0, 35, 70, 105, 140]} />
              <Tooltip contentStyle={{ background: cardBg, border: `1px solid ${border}`, borderRadius: 8, fontFamily: font, fontSize: 12, boxShadow: "0 4px 12px rgba(0,0,0,0.08)" }} cursor={{ fill: "rgba(0,0,0,0.03)" }} />
              <ReferenceLine y={100} stroke="#dc2626" strokeDasharray="6 4" strokeWidth={1.5} strokeOpacity={0.4} />
              <Bar dataKey="predicted" name="Predicted" fill="#2563eb" fillOpacity={0.45} radius={[4,4,0,0]} />
              <Bar dataKey="actual" name="Actual" fill="#4b5563" radius={[4,4,0,0]} />
            </BarChart>
          </ResponsiveContainer>
        </div>
      </div>

      {/* AUTO-OPTIMIZER */}
      <div style={{ background: cardBg, borderRadius: 10, border: `1px solid ${border}`, padding: 20 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 16 }}>
          <div style={{ display: "flex", gap: 10 }}>
            <div style={{ background: "#eff6ff", borderRadius: 8, padding: 8 }}><window.Icon name="Zap" size={18} color="#2563eb" /></div>
            <div>
              <h2 style={{ fontSize: 15, fontWeight: 700, color: fg, fontFamily: font, margin: 0 }}>AutoOptimizer</h2>
              <p style={{ fontSize: 11, color: muted, fontFamily: font, marginTop: 2 }}>Continuously optimizing workflow configs to maximize conversion rates</p>
              <p style={{ fontSize: 10, color: muted, fontFamily: font, marginTop: 2 }}>Last optimization cycle: 3 hours ago</p>
            </div>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
            <span style={{ fontSize: 12, fontWeight: 600, fontFamily: font, color: fg }}>AutoOptimizer:</span>
            <button onClick={() => setAutoOptimizerEnabled(!autoOptimizerEnabled)} style={{ width: 36, height: 20, borderRadius: 10, background: autoOptimizerEnabled ? "#22c55e" : "#d1d5db", border: "none", cursor: "pointer", position: "relative", transition: "background 0.2s" }}>
              <span style={{ position: "absolute", top: 3, left: autoOptimizerEnabled ? 19 : 3, width: 14, height: 14, borderRadius: 7, background: "white", transition: "left 0.2s" }} />
            </button>
            <span style={{ fontSize: 12, fontWeight: 700, fontFamily: font, color: autoOptimizerEnabled ? "#22c55e" : muted }}>{autoOptimizerEnabled ? "ON" : "OFF"}</span>
          </div>
        </div>
        <div style={{ background: "#f9fafb", borderRadius: 10, padding: 16, marginBottom: 16 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 8 }}>
            <span style={{ fontSize: 13, fontWeight: 700, color: fg, fontFamily: font }}>Optimization Impact</span>
            <div style={{ textAlign: "right" }}>
              <div style={{ fontSize: 22, fontWeight: 800, color: "#22c55e", fontFamily: font }}>+3.2%</div>
              <div style={{ fontSize: 10, color: muted, fontFamily: font }}>conversion lift since enabled</div>
            </div>
          </div>
          <ResponsiveContainer width="100%" height={180}>
            <ComposedChart data={conversionData}>
              <CartesianGrid strokeDasharray="3 3" stroke={border} />
              <XAxis dataKey="date" tick={{ fill: muted, fontSize: 10 }} stroke={border} />
              <YAxis domain={[23, 29]} tick={{ fill: muted, fontSize: 10 }} stroke={border} />
              <Tooltip contentStyle={{ background: cardBg, border: `1px solid ${border}`, borderRadius: 6, fontFamily: font, fontSize: 11 }} />
              <Legend wrapperStyle={{ fontFamily: font, fontSize: 10 }} />
              <Area type="monotone" dataKey="actual" fill="#22c55e" fillOpacity={0.15} stroke="none" legendType="none" />
              <Line type="monotone" dataKey="baseline" name="Baseline" stroke="#6B7280" strokeDasharray="5 5" strokeWidth={1.5} dot={false} />
              <Line type="monotone" dataKey="actual" name="Actual Conversion" stroke="#2563eb" strokeWidth={2.5} dot={{ fill: "#2563eb", r: 3 }} />
            </ComposedChart>
          </ResponsiveContainer>
        </div>
        <div>
          <span style={{ fontSize: 13, fontWeight: 700, color: fg, fontFamily: font, display: "block", marginBottom: 10 }}>Workflows Being Optimized</span>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 10 }}>
            {workflows.map(wf => {
              const isOn = workflowToggles[wf.id];
              return (
                <div key={wf.id} style={{ background: "#f9fafb", borderRadius: 10, border: `1px solid ${border}`, padding: 14 }}>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 6 }}>
                    <div>
                      <div style={{ fontSize: 12, fontWeight: 700, color: fg, fontFamily: font }}>{wf.name}</div>
                      <div style={{ display: "flex", alignItems: "center", gap: 4, marginTop: 2 }}>
                        <span style={{ fontSize: 16, fontWeight: 800, color: fg, fontFamily: font }}>{wf.conversion}%</span>
                        {wf.trend === "up" && <window.Icon name="TrendingUp" size={13} color="#22c55e" />}
                      </div>
                    </div>
                    <span style={{ fontSize: 10, fontWeight: 600, fontFamily: font, padding: "2px 7px", borderRadius: 4, background: wf.status === "optimizing" ? "#eff6ff" : wf.status === "stable" ? "#dcfce7" : "#f3f4f6", color: wf.status === "optimizing" ? "#2563eb" : wf.status === "stable" ? "#166534" : muted }}>{wf.status === "optimizing" && "● "}{wf.status.charAt(0).toUpperCase() + wf.status.slice(1)}</span>
                  </div>
                  <div style={{ marginBottom: 8 }}><window.Sparkline data={wf.sparkline} color={wf.status === "disabled" ? "#9ca3af" : "#2563eb"} /></div>
                  <div style={{ display: "flex", alignItems: "center", gap: 4, borderTop: `1px solid ${border}`, paddingTop: 8 }}>
                    <span style={{ fontSize: 10, color: muted, fontFamily: font, flex: 1 }}>AutoOptimizer:</span>
                    <button onClick={() => setWorkflowToggles({ ...workflowToggles, [wf.id]: !isOn })} style={{ width: 30, height: 16, borderRadius: 8, background: isOn ? "#22c55e" : "#d1d5db", border: "none", cursor: "pointer", position: "relative" }}>
                      <span style={{ position: "absolute", top: 2, left: isOn ? 16 : 2, width: 12, height: 12, borderRadius: 6, background: "white", transition: "left 0.2s" }} />
                    </button>
                    <span style={{ fontSize: 10, fontWeight: 700, fontFamily: font, color: isOn ? "#22c55e" : muted }}>{isOn ? "ON" : "OFF"}</span>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
      {strategyToast && (
        <div style={{ position: "fixed", bottom: 20, right: 20, background: "#0f172a", color: "white", padding: "12px 16px", borderRadius: 10, fontSize: 12, fontFamily: font, fontWeight: 700, display: "flex", alignItems: "center", gap: 10, boxShadow: "0 10px 30px rgba(0,0,0,0.25)", zIndex: 1100, border: "1px solid rgba(74,222,128,0.3)" }}>
          <window.Icon name="Check" size={14} color="#4ade80" />
          <span>Strategy saved — Max will use these for future recommendations.</span>
        </div>
      )}
      <window.ConfigureStrategyModal
        open={strategyOpen}
        onClose={() => setStrategyOpen(false)}
        initial={strategy}
        onSave={(next) => {
          setStrategy(next);
          setStrategyToast(true);
          setTimeout(() => setStrategyToast(null), 3500);
        }}
      />
      <window.ConfirmActivateModal
        open={!!confirmAction}
        action={confirmAction}
        onClose={() => setConfirmAction(null)}
        onConfirm={activateAction}
      />
      <window.DetailsModal
        open={!!detailsAction}
        action={detailsAction}
        onClose={() => setDetailsAction(null)}
        onActivate={(a) => setConfirmAction(a)}
      />
      {activatedToast && (
        <div style={{ position: "fixed", bottom: 20, right: 20, background: "#0f172a", color: "white", padding: "12px 16px", borderRadius: 10, fontSize: 12, fontFamily: font, fontWeight: 700, display: "flex", alignItems: "center", gap: 10, boxShadow: "0 10px 30px rgba(0,0,0,0.25)", zIndex: 1100, border: "1px solid rgba(74,222,128,0.3)", maxWidth: 360 }}>
          <window.Icon name="Zap" size={14} color="#4ade80" />
          <div>
            <div>Activated — Max is running it now.</div>
            <div style={{ fontSize: 10, color: "rgba(255,255,255,0.6)", fontWeight: 500, marginTop: 2 }}>{activatedToast.rec}</div>
          </div>
        </div>
      )}
    </div>
  );
}

window.MaxHomePage = MaxHomePage;
})();
