(function () {

const { useState: useStateCS, useEffect: useEffectCS } = React;

const STRATEGIC_GOALS = [
  { id: "increase-ticket", label: "Increase average ticket", desc: "Bias Max toward upsells, premium options, and equipment replacement over repair.", icon: "TrendingUp" },
  { id: "increase-conversion", label: "Increase conversion rate", desc: "Prioritize speed-to-lead, follow-ups, and booking automations.", icon: "Target" },
  { id: "fill-capacity", label: "Fill technician capacity", desc: "Push idle slots — re-engage stale estimates, lapsed customers, lower-priority leads.", icon: "Users" },
  { id: "grow-memberships", label: "Grow membership base", desc: "Convert one-time customers to recurring; prioritize agreement offers.", icon: "Award" },
  { id: "improve-retention", label: "Improve customer retention", desc: "Maintenance reminders, equipment-aging follow-ups, post-job NPS.", icon: "Heart" },
  { id: "reduce-cac", label: "Reduce cost per acquisition", desc: "Optimize ad spend toward lower-CAC channels; cap underperforming campaigns.", icon: "DollarSign" },
];

const TRADES = ["HVAC", "Plumbing", "Electrical"];

function ConfigureStrategyModal({ open, onClose, initial, onSave }) {
  const [tab, setTab] = useStateCS("goals");
  const [draft, setDraft] = useStateCS(initial);

  useEffectCS(() => { if (open) setDraft(initial); }, [open, initial]);
  useEffectCS(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  if (!open) return null;

  const D = window.MAX_DATA;
  const { font, fg, muted, border, cardBg } = D;

  const setField = (path, value) => {
    setDraft(d => {
      const next = JSON.parse(JSON.stringify(d));
      const keys = path.split(".");
      let obj = next;
      for (let i = 0; i < keys.length - 1; i++) obj = obj[keys[i]];
      obj[keys[keys.length - 1]] = value;
      return next;
    });
  };

  const toggleGoal = (id) => {
    setDraft(d => {
      const has = d.goals.includes(id);
      let next = has ? d.goals.filter(g => g !== id) : [...d.goals, id];
      if (next.length > 3) next = next.slice(-3);
      return { ...d, goals: next };
    });
  };

  const setGoalPriority = (id, priority) => {
    // priority is rank 1..3 by reordering
    setDraft(d => {
      const without = d.goals.filter(g => g !== id);
      const next = [...without];
      next.splice(priority - 1, 0, id);
      return { ...d, goals: next.slice(0, 3) };
    });
  };

  const tabs = [
    { id: "goals", label: "Strategic goals", icon: "Target" },
    { id: "marketing", label: "Marketing budget", icon: "Megaphone" },
    { id: "staffing", label: "Staffing plan", icon: "Users" },
    { id: "constraints", label: "Hard constraints", icon: "Shield" },
  ];

  const totalAdSpend = TRADES.reduce((s, t) => s + (draft.marketing[t]?.monthly || 0), 0);
  const totalHires = TRADES.reduce((s, t) => s + (draft.staffing[t]?.plannedHires || 0), 0);
  const currentHeadcount = TRADES.reduce((s, t) => s + (draft.staffing[t]?.current || 0), 0);

  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: 920, maxHeight: "92vh", display: "flex", flexDirection: "column", boxShadow: "0 30px 80px rgba(0,0,0,0.35)", overflow: "hidden", border: `1px solid ${border}` }}>
        {/* Header */}
        <div style={{ padding: "18px 24px", borderBottom: `1px solid ${border}`, display: "flex", alignItems: "center", gap: 14, background: "linear-gradient(135deg, #f8fafc 0%, #ffffff 100%)" }}>
          <div style={{ background: "#dbeafe", borderRadius: 10, padding: 10, border: "1px solid #bfdbfe" }}><window.Icon name="Settings" size={20} color="#2563eb" /></div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 18, fontWeight: 800, color: fg, fontFamily: font, letterSpacing: -0.3 }}>Configure Strategy</div>
            <div style={{ fontSize: 12, color: muted, fontFamily: font, marginTop: 2 }}>Set goals, budget, staffing, and constraints. Max uses these to prioritize automations and recommendations.</div>
          </div>
          <button onClick={onClose} style={{ background: "transparent", border: "none", cursor: "pointer", padding: 8, fontSize: 18, color: muted, fontFamily: font, lineHeight: 1 }}>✕</button>
        </div>

        {/* Tabs */}
        <div style={{ display: "flex", padding: "0 24px", gap: 4, borderBottom: `1px solid ${border}`, background: "#fafbfc" }}>
          {tabs.map(t => (
            <button key={t.id} onClick={() => setTab(t.id)} style={{ display: "flex", alignItems: "center", gap: 6, padding: "12px 14px", background: "transparent", border: "none", borderBottom: tab === t.id ? "2px solid #2563eb" : "2px solid transparent", cursor: "pointer", fontSize: 12, fontFamily: font, fontWeight: 700, color: tab === t.id ? "#2563eb" : muted, marginBottom: -1 }}>
              <window.Icon name={t.icon} size={13} color={tab === t.id ? "#2563eb" : muted} /> {t.label}
            </button>
          ))}
        </div>

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

          {tab === "goals" && (
            <div>
              <SectionTitle title="What should Max optimize for?" subtitle="Pick up to 3 goals. Drag-rank by priority — Max weighs recommendations accordingly." />
              <div style={{ marginBottom: 14 }}>
                <div style={{ fontSize: 11, fontWeight: 700, color: muted, fontFamily: font, textTransform: "uppercase", letterSpacing: 0.6, marginBottom: 8 }}>Selected ({draft.goals.length}/3)</div>
                {draft.goals.length === 0 ? (
                  <div style={{ padding: "14px 16px", background: cardBg, border: `1px dashed ${border}`, borderRadius: 8, fontSize: 12, color: muted, fontFamily: font, fontStyle: "italic" }}>No goals selected yet — pick from below.</div>
                ) : (
                  <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                    {draft.goals.map((id, i) => {
                      const g = STRATEGIC_GOALS.find(x => x.id === id);
                      return (
                        <div key={id} style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 14px", background: "white", border: "1px solid #bfdbfe", borderLeft: "3px solid #2563eb", borderRadius: 8 }}>
                          <span style={{ width: 22, height: 22, borderRadius: 99, background: "#2563eb", color: "white", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 11, fontWeight: 800, fontFamily: font }}>{i + 1}</span>
                          <window.Icon name={g.icon} size={14} color="#2563eb" />
                          <span style={{ fontSize: 13, fontWeight: 700, color: fg, fontFamily: font, flex: 1 }}>{g.label}</span>
                          <div style={{ display: "flex", gap: 2 }}>
                            {i > 0 && <button onClick={() => setGoalPriority(id, i)} style={btnGhost(font, fg, border)}>↑</button>}
                            {i < draft.goals.length - 1 && <button onClick={() => setGoalPriority(id, i + 2)} style={btnGhost(font, fg, border)}>↓</button>}
                            <button onClick={() => toggleGoal(id)} style={{ ...btnGhost(font, fg, border), color: "#dc2626" }}>✕</button>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>

              <div style={{ fontSize: 11, fontWeight: 700, color: muted, fontFamily: font, textTransform: "uppercase", letterSpacing: 0.6, marginTop: 18, marginBottom: 8 }}>Available goals</div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
                {STRATEGIC_GOALS.filter(g => !draft.goals.includes(g.id)).map(g => (
                  <button key={g.id} onClick={() => toggleGoal(g.id)} style={{ display: "flex", alignItems: "flex-start", gap: 10, padding: "12px 14px", background: cardBg, border: `1px solid ${border}`, borderRadius: 8, cursor: "pointer", textAlign: "left", fontFamily: font, transition: "all 0.15s" }}
                    onMouseEnter={e => { e.currentTarget.style.borderColor = "#bfdbfe"; e.currentTarget.style.background = "#f8faff"; }}
                    onMouseLeave={e => { e.currentTarget.style.borderColor = border; e.currentTarget.style.background = cardBg; }}>
                    <div style={{ background: "#f1f5f9", borderRadius: 6, padding: 6, marginTop: 1 }}><window.Icon name={g.icon} size={13} color="#475569" /></div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 13, fontWeight: 700, color: fg, marginBottom: 2 }}>{g.label}</div>
                      <div style={{ fontSize: 11, color: muted, lineHeight: 1.4 }}>{g.desc}</div>
                    </div>
                    <span style={{ fontSize: 14, color: muted, marginTop: 2 }}>+</span>
                  </button>
                ))}
              </div>
            </div>
          )}

          {tab === "marketing" && (
            <div>
              <SectionTitle title="Marketing budget" subtitle="Set monthly ad spend caps per trade. Max won't recommend increases above these caps without explicit approval." />
              <div style={{ background: cardBg, border: `1px solid ${border}`, borderRadius: 10, overflow: "hidden", marginBottom: 18 }}>
                <div style={{ display: "grid", gridTemplateColumns: "120px 1fr 130px 130px", padding: "10px 18px", background: "#f8fafc", borderBottom: `1px solid ${border}`, fontSize: 10, fontWeight: 800, color: muted, fontFamily: font, textTransform: "uppercase", letterSpacing: 0.6 }}>
                  <span>Trade</span><span>Monthly cap</span><span>Channels</span><span style={{ textAlign: "right" }}>Last 30d spend</span>
                </div>
                {TRADES.map(t => {
                  const m = draft.marketing[t] || { monthly: 0, channels: [], spent: 0 };
                  return (
                    <div key={t} style={{ display: "grid", gridTemplateColumns: "120px 1fr 130px 130px", alignItems: "center", padding: "14px 18px", borderBottom: `1px solid ${border}`, fontFamily: font }}>
                      <span style={{ fontSize: 13, fontWeight: 700, color: fg }}>{t}</span>
                      <div style={{ display: "flex", alignItems: "center", gap: 10, paddingRight: 16 }}>
                        <span style={{ fontSize: 12, color: muted }}>$</span>
                        <input type="number" value={m.monthly} onChange={e => setField(`marketing.${t}.monthly`, +e.target.value)} style={inputStyle(font, fg, border, 110)} />
                        <input type="range" min={0} max={50000} step={500} value={m.monthly} onChange={e => setField(`marketing.${t}.monthly`, +e.target.value)} style={{ flex: 1, accentColor: "#2563eb" }} />
                      </div>
                      <div style={{ fontSize: 11, color: muted }}>{m.channels.join(", ") || "—"}</div>
                      <div style={{ textAlign: "right" }}>
                        <span style={{ fontSize: 13, fontWeight: 700, color: m.spent > m.monthly ? "#dc2626" : fg, fontFamily: font }}>${m.spent.toLocaleString()}</span>
                        <div style={{ fontSize: 10, color: m.spent > m.monthly ? "#dc2626" : muted, marginTop: 1 }}>{m.monthly ? Math.round((m.spent / m.monthly) * 100) : 0}% of cap</div>
                      </div>
                    </div>
                  );
                })}
                <div style={{ display: "grid", gridTemplateColumns: "120px 1fr 130px 130px", padding: "12px 18px", background: "#f8fafc", fontFamily: font }}>
                  <span style={{ fontSize: 12, fontWeight: 800, color: fg }}>Total / month</span>
                  <span></span><span></span>
                  <span style={{ fontSize: 14, fontWeight: 800, color: fg, textAlign: "right" }}>${totalAdSpend.toLocaleString()}</span>
                </div>
              </div>

              <Toggle font={font} fg={fg} muted={muted} border={border} label="Allow Max to reallocate budget between trades" sub="When one trade is over capacity, Max can temporarily shift unused budget to others." checked={draft.marketing.allowReallocate} onChange={v => setField("marketing.allowReallocate", v)} />
              <Toggle font={font} fg={fg} muted={muted} border={border} label="Auto-pause campaigns when over capacity" sub="If a trade is booked solid for 7+ days, Max will pause its campaigns automatically." checked={draft.marketing.autoPauseOverCapacity} onChange={v => setField("marketing.autoPauseOverCapacity", v)} />
            </div>
          )}

          {tab === "staffing" && (
            <div>
              <SectionTitle title="Staffing plan" subtitle="Tell Max how your team will grow. It uses this to forecast capacity and recommend the right automations to fill it." />
              <div style={{ background: cardBg, border: `1px solid ${border}`, borderRadius: 10, overflow: "hidden", marginBottom: 18 }}>
                <div style={{ display: "grid", gridTemplateColumns: "120px 110px 1fr 130px", padding: "10px 18px", background: "#f8fafc", borderBottom: `1px solid ${border}`, fontSize: 10, fontWeight: 800, color: muted, fontFamily: font, textTransform: "uppercase", letterSpacing: 0.6 }}>
                  <span>Trade</span><span>Current</span><span>Planned hires (12 mo)</span><span style={{ textAlign: "right" }}>Target headcount</span>
                </div>
                {TRADES.map(t => {
                  const s = draft.staffing[t] || { current: 0, plannedHires: 0 };
                  return (
                    <div key={t} style={{ display: "grid", gridTemplateColumns: "120px 110px 1fr 130px", alignItems: "center", padding: "14px 18px", borderBottom: `1px solid ${border}`, fontFamily: font }}>
                      <span style={{ fontSize: 13, fontWeight: 700, color: fg }}>{t}</span>
                      <input type="number" value={s.current} onChange={e => setField(`staffing.${t}.current`, +e.target.value)} style={inputStyle(font, fg, border, 80)} />
                      <div style={{ display: "flex", alignItems: "center", gap: 10, paddingRight: 16 }}>
                        <input type="range" min={0} max={20} step={1} value={s.plannedHires} onChange={e => setField(`staffing.${t}.plannedHires`, +e.target.value)} style={{ flex: 1, accentColor: "#16a34a" }} />
                        <span style={{ fontSize: 13, fontWeight: 800, color: s.plannedHires > 0 ? "#16a34a" : muted, fontFamily: font, minWidth: 28, textAlign: "right" }}>+{s.plannedHires}</span>
                      </div>
                      <span style={{ fontSize: 14, fontWeight: 800, color: fg, textAlign: "right" }}>{s.current + s.plannedHires} techs</span>
                    </div>
                  );
                })}
                <div style={{ display: "grid", gridTemplateColumns: "120px 110px 1fr 130px", padding: "12px 18px", background: "#f8fafc", fontFamily: font }}>
                  <span style={{ fontSize: 12, fontWeight: 800, color: fg }}>Total</span>
                  <span style={{ fontSize: 13, fontWeight: 700, color: fg }}>{currentHeadcount}</span>
                  <span style={{ fontSize: 13, fontWeight: 700, color: "#16a34a" }}>+{totalHires} planned</span>
                  <span style={{ fontSize: 14, fontWeight: 800, color: fg, textAlign: "right" }}>{currentHeadcount + totalHires} techs</span>
                </div>
              </div>

              <div style={{ background: "#eff6ff", border: "1px solid #bfdbfe", borderRadius: 8, padding: "12px 14px", display: "flex", gap: 10, alignItems: "flex-start", fontFamily: font }}>
                <window.Icon name="Info" size={14} color="#2563eb" />
                <div style={{ fontSize: 12, color: "#1e40af", lineHeight: 1.5 }}>
                  Based on this plan, Max projects you'll have <strong>~{Math.round((currentHeadcount + totalHires) * 22)} jobs/week</strong> of capacity in 12 months — about <strong>{Math.round(((totalHires) / Math.max(currentHeadcount, 1)) * 100)}% more</strong> than today. It will prioritize lead-gen and conversion automations to fill that capacity.
                </div>
              </div>
            </div>
          )}

          {tab === "constraints" && (
            <div>
              <SectionTitle title="Hard constraints" subtitle="Lines Max won't cross. These override goals and recommendations." />
              <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                <Toggle font={font} fg={fg} muted={muted} border={border} label="Never reduce headcount in recommendations" checked={draft.constraints.neverReduceHeadcount} onChange={v => setField("constraints.neverReduceHeadcount", v)} />
                <Toggle font={font} fg={fg} muted={muted} border={border} label="Require approval for changes &gt; $5K impact" checked={draft.constraints.requireApprovalLarge} onChange={v => setField("constraints.requireApprovalLarge", v)} />
                <Toggle font={font} fg={fg} muted={muted} border={border} label="Pause customer-facing automations on holidays" checked={draft.constraints.pauseOnHolidays} onChange={v => setField("constraints.pauseOnHolidays", v)} />
                <Toggle font={font} fg={fg} muted={muted} border={border} label="No outbound SMS before 8 AM or after 8 PM local" checked={draft.constraints.respectQuietHours} onChange={v => setField("constraints.respectQuietHours", v)} />
                <div style={{ background: cardBg, border: `1px solid ${border}`, borderRadius: 8, padding: "12px 14px" }}>
                  <div style={{ fontSize: 12, fontWeight: 700, color: fg, fontFamily: font, marginBottom: 6 }}>Minimum gross margin</div>
                  <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                    <input type="range" min={20} max={70} step={1} value={draft.constraints.minMargin} onChange={e => setField("constraints.minMargin", +e.target.value)} style={{ flex: 1, accentColor: "#2563eb" }} />
                    <span style={{ fontSize: 16, fontWeight: 800, color: fg, fontFamily: font, minWidth: 50, textAlign: "right" }}>{draft.constraints.minMargin}%</span>
                  </div>
                  <div style={{ fontSize: 11, color: muted, fontFamily: font, marginTop: 6 }}>Max won't recommend ad spend or promotions that would push margin below this threshold.</div>
                </div>
              </div>
            </div>
          )}
        </div>

        {/* Footer */}
        <div style={{ padding: "14px 24px", borderTop: `1px solid ${border}`, display: "flex", alignItems: "center", justifyContent: "space-between", background: cardBg }}>
          <span style={{ fontSize: 11, color: muted, fontFamily: font }}>
            <window.Icon name="Lock" size={11} /> Changes take effect immediately and apply to future recommendations.
          </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 }}>Cancel</button>
            <button onClick={() => { onSave(draft); 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" /> Save strategy
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

function SectionTitle({ title, subtitle }) {
  const { font, fg, muted } = window.MAX_DATA;
  return (
    <div style={{ marginBottom: 14 }}>
      <div style={{ fontSize: 15, fontWeight: 800, color: fg, fontFamily: font, letterSpacing: -0.2 }}>{title}</div>
      <div style={{ fontSize: 12, color: muted, fontFamily: font, marginTop: 3, lineHeight: 1.5 }}>{subtitle}</div>
    </div>
  );
}

function Toggle({ font, fg, muted, border, label, sub, checked, onChange }) {
  return (
    <label style={{ display: "flex", alignItems: "flex-start", gap: 12, padding: "12px 14px", background: "white", border: `1px solid ${border}`, borderRadius: 8, cursor: "pointer", fontFamily: font, marginBottom: 8 }}>
      <button type="button" onClick={() => onChange(!checked)} style={{ width: 32, height: 18, borderRadius: 99, background: checked ? "#2563eb" : "#cbd5e1", border: "none", position: "relative", cursor: "pointer", flexShrink: 0, marginTop: 1, transition: "background 0.15s" }}>
        <span style={{ position: "absolute", top: 2, left: checked ? 16 : 2, width: 14, height: 14, borderRadius: 99, background: "white", transition: "left 0.15s" }} />
      </button>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 13, fontWeight: 700, color: fg }}>{label}</div>
        {sub && <div style={{ fontSize: 11, color: muted, marginTop: 2, lineHeight: 1.4 }}>{sub}</div>}
      </div>
    </label>
  );
}

function btnGhost(font, fg, border) {
  return { padding: "4px 8px", borderRadius: 5, background: "transparent", color: fg, border: `1px solid ${border}`, cursor: "pointer", fontSize: 11, fontWeight: 700, fontFamily: font };
}

function inputStyle(font, fg, border, width) {
  return { width, padding: "6px 10px", borderRadius: 6, border: `1px solid ${border}`, fontSize: 13, fontFamily: font, fontWeight: 600, color: fg, background: "white", outline: "none" };
}

window.ConfigureStrategyModal = ConfigureStrategyModal;
window.DEFAULT_STRATEGY = {
  goals: ["increase-conversion", "fill-capacity"],
  marketing: {
    HVAC:       { monthly: 12000, channels: ["Google Ads", "Angi"], spent: 8400 },
    Plumbing:   { monthly: 6000,  channels: ["Google Ads"],         spent: 4200 },
    Electrical: { monthly: 3000,  channels: ["Google Ads"],         spent: 1800 },
    allowReallocate: true,
    autoPauseOverCapacity: false,
  },
  staffing: {
    HVAC:       { current: 18, plannedHires: 4 },
    Plumbing:   { current: 12, plannedHires: 2 },
    Electrical: { current: 6,  plannedHires: 1 },
  },
  constraints: {
    neverReduceHeadcount: true,
    requireApprovalLarge: true,
    pauseOnHolidays: true,
    respectQuietHours: true,
    minMargin: 35,
  },
};

})();
