/* Calculator — the rep quote builder, now driven by the real pricing engine
   (window.OneDayPricing) over the real door catalog (window.PRICING_CFG). */

const C = window.Ds1Threshold_e046d3;

const BAND = {
  "dark-green": { solid: "var(--status-sold-solid)", soft: "var(--status-sold-bg)", fg: "var(--status-sold-fg)" },
  green:        { solid: "var(--color-primary)",     soft: "var(--color-primary-soft)", fg: "var(--color-primary-deep)" },
  yellow:       { solid: "var(--status-pending-solid)", soft: "var(--status-pending-bg)", fg: "var(--status-pending-fg)" },
  red:          { solid: "var(--status-lost-solid)",  soft: "var(--status-lost-bg)",  fg: "var(--status-lost-fg)" },
};

function SectionCard({ icon, title, children, right }) {
  return (
    <C.Card style={{ marginBottom: 16 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 16 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{ width: 32, height: 32, borderRadius: "var(--radius-md)", background: "var(--color-primary-soft)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--color-primary-deep)" }}>
            <Icon name={icon} size={17} />
          </div>
          <h3 style={{ margin: 0, fontSize: "var(--text-lg)", fontWeight: 600, color: "var(--text-primary)" }}>{title}</h3>
        </div>
        {right}
      </div>
      {children}
    </C.Card>
  );
}

// ── Door picker row ──────────────────────────────────────────────────────────
function DoorPicker({ catalog, onAdd }) {
  const cols = window.OneDayPricing.collections(catalog);
  const [collection, setCollection] = React.useState(cols[2] || cols[0]);
  const styles = window.OneDayPricing.stylesIn(catalog, collection);
  const [style, setStyle] = React.useState(styles[0]);
  const variants = window.OneDayPricing.variantsFor(catalog, style);
  const [variantIdx, setVariantIdx] = React.useState(0);
  const [qty, setQty] = React.useState(1);

  React.useEffect(() => { const s = window.OneDayPricing.stylesIn(catalog, collection); setStyle(s[0]); setVariantIdx(0); }, [collection]);
  React.useEffect(() => { setVariantIdx(0); }, [style]);

  const v = variants[variantIdx] || variants[0];

  return (
    <div style={{ display: "grid", gridTemplateColumns: "1.3fr 1.6fr 1fr 64px auto", gap: 10, alignItems: "end" }}>
      <C.Select label="Collection" value={collection} onChange={(e) => setCollection(e.target.value)} options={cols} />
      <C.Select label="Door Style" value={style} onChange={(e) => setStyle(e.target.value)} options={styles} />
      <C.Select label="Core · Height" value={String(variantIdx)} onChange={(e) => setVariantIdx(Number(e.target.value))}
        options={variants.map((x, i) => ({ value: String(i), label: `${x.core} · ${x.height} — ${fmt(x.list)}` }))} />
      <C.Input label="Qty" type="number" min="1" value={qty} onChange={(e) => setQty(Math.max(1, Number(e.target.value) || 1))} />
      <C.Button variant="primary" onClick={() => v && onAdd({ style: v.style, core: v.core, height: v.height, qty })}>
        <Icon name="Plus" size={16} />Add
      </C.Button>
    </div>
  );
}

function Calculator({ onPresent, onSaved, initialQuote }) {
  const cfg = window.PRICING_CFG;
  const engine = window.OneDayPricing;
  const seed = (initialQuote && initialQuote.state) || {};

  const [cust, setCust] = React.useState(() => ({
    name: (initialQuote && initialQuote.customer) || "",
    phone: (initialQuote && initialQuote.phone) || "",
    email: (initialQuote && initialQuote.email) || "",
    address: (initialQuote && initialQuote.address) || "",
  }));
  const [contactOpen, setContactOpen] = React.useState(false);
  const [interior, setInterior] = React.useState(seed.interior || [
    { style: "Cape Cod - M Series", core: "Solid", height: "6/8", qty: 6 },
    { style: "Cape Cod - M Series", core: "Solid", height: "8/0", qty: 2 },
  ]);
  const [customItems, setCustomItems] = React.useState(seed.customItems || []);
  const [options, setOptions] = React.useState(seed.options || { paint: true, install: true, hardwareInstall: true, disposal: true, freight: true, measure3d: true, customColor: false, barn: false, casingSides: 0 });
  const [discounts, setDiscounts] = React.useState(seed.discounts || { bogo: false, volume: true, military: false, hundredOff: false, freeInstall: false, wholeHome99: false, thirtyOff: false, freeHardware: false });
  const [saved, setSaved] = React.useState(false);
  const [copts, setCopts] = React.useState(() => Object.assign({ paintName: "Pure White", paintCode: "SW 7005", hardwareBrand: "Emtek", hardwareFinish: "Matte Black", hardwareBy: "Company", notes: "" }, seed.contractOpts || {}));
  const setCopt = (k, v) => setCopts((o) => ({ ...o, [k]: v }));
  const notes = copts.notes;
  const setNotes = (v) => setCopt("notes", v);
  const doorCount = interior.reduce((s, l) => s + (Number(l.qty) || 0), 0);
  const ccLookup = copts.customColorCode ? window.swLookup(copts.customColorCode) : null;
  const ccHex = copts.customColorHex || (ccLookup && ccLookup.hex) || null;
  const ccName = copts.customColorName || (ccLookup && ccLookup.name) || "";
  const applyCustomCode = (raw) => { const r = window.swLookup(raw); setCopts((o) => ({ ...o, customColorCode: raw, customColorName: r ? r.name : "", customColorHex: r ? r.hex : null })); };

  const quote = engine.computeQuote({ interior, exterior: [], customItems, options: { ...options, customColorQty: copts.customColorQty }, discounts }, cfg);
  React.useEffect(() => { window.__OD_ACTIVE = { interior, customItems, options: { ...options, customColorQty: copts.customColorQty }, discounts, customer: { ...cust }, contractOpts: { ...copts } }; }, [interior, customItems, options, discounts, cust, copts]);

  const setCustField = (k) => (e) => setCust((c) => ({ ...c, [k]: e.target.value }));
  // Contact autocomplete — pulls from the existing CRM contacts (e31_contacts mirror).
  const contactMatches = (() => {
    const q = (cust.name || "").trim().toLowerCase();
    if (!q || !window.CRM) return [];
    return window.CRM.contacts.filter((c) => {
      const full = `${c.first_name} ${c.last_name}`.toLowerCase();
      return full.includes(q) || (c.phone || "").includes(q) || (c.email || "").toLowerCase().includes(q);
    }).slice(0, 6);
  })();
  const pickContact = (c) => {
    const job = window.CRM && window.CRM.jobs.find((j) => j.contact_id === c.id);
    setCust({ name: `${c.first_name} ${c.last_name}`, phone: c.phone || "", email: c.email || "", address: (job && job.full_address) || "" });
    setContactOpen(false);
  };
  // Create a new CRM contact from the typed customer (when not already on file).
  const [contactSaved, setContactSaved] = React.useState(false);
  const existsContact = !!(window.CRM && cust.name.trim() && window.CRM.contacts.some((c) => `${c.first_name} ${c.last_name}`.trim().toLowerCase() === cust.name.trim().toLowerCase()));
  React.useEffect(() => { setContactSaved(false); }, [cust.name]);
  const createContact = () => {
    if (!window.CRM || !cust.name.trim()) return;
    const parts = cust.name.trim().split(/\s+/);
    const rec = { id: "c-new-" + Date.now().toString(36), first_name: parts[0], last_name: parts.slice(1).join(" "), phone: cust.phone || "", email: cust.email || "", address: cust.address || "" };
    window.CRM.contacts.unshift(rec);
    setContactSaved(true);
  };
  const buildRecord = () => {
    const isSold = !!(initialQuote && initialQuote.status === "sold");
    return {
      id: (initialQuote && initialQuote.id) || window.OneDayStore.nextId(),
      customer: cust.name, address: cust.address, email: cust.email, phone: cust.phone,
      rep: (initialQuote && initialQuote.rep) || "marco",
      date: (initialQuote && initialQuote.date) || new Date().toLocaleString("en-US", { month: "short", day: "numeric" }),
      period: (initialQuote && initialQuote.period) || (window.PAY_PERIODS && window.PAY_PERIODS[0] && window.PAY_PERIODS[0].id),
      status: (initialQuote && initialQuote.status) || "pending",
      total: quote.promotionalTotal,
      margin: quote.margin, rate: quote.commissionRate,
      commission: isSold ? quote.commissionAmount : 0,
      state: { interior, customItems, options: { ...options, customColorQty: copts.customColorQty }, discounts, contractOpts: { ...copts } },
    };
  };
  const handleSave = () => {
    const rec = buildRecord();
    window.OneDayStore.upsert(rec);
    setSaved(true);
    if (onSaved) onSaved(rec);
  };
  const handlePresent = () => { window.__OD_ACTIVE = { interior, customItems, options: { ...options, customColorQty: copts.customColorQty }, discounts, customer: { ...cust }, contractOpts: { ...copts } }; if (onPresent) onPresent(); };
  const band = BAND[quote.commissionTier.band] || BAND.green;

  const addDoor = (d) => setInterior((prev) => {
    const i = prev.findIndex((p) => p.style === d.style && p.core === d.core && p.height === d.height);
    if (i >= 0) { const copy = [...prev]; copy[i] = { ...copy[i], qty: copy[i].qty + d.qty }; return copy; }
    return [...prev, d];
  });
  const removeDoor = (idx) => setInterior((prev) => prev.filter((_, i) => i !== idx));
  const setQty = (idx, qty) => setInterior((prev) => prev.map((p, i) => i === idx ? { ...p, qty: Math.max(1, qty) } : p));
  const addCustom = () => setCustomItems((prev) => [...prev, { label: "", qty: 1, price: 0 }]);
  const setCustom = (idx, patch) => setCustomItems((prev) => prev.map((c, i) => i === idx ? { ...c, ...patch } : c));
  const removeCustom = (idx) => setCustomItems((prev) => prev.filter((_, i) => i !== idx));
  const toggleOpt = (k) => setOptions((o) => ({ ...o, [k]: !o[k] }));
  const toggleDisc = (k) => setDiscounts((d) => ({ ...d, [k]: !d[k] }));

  return (
    <div style={{ maxWidth: "var(--content-max)", margin: "0 auto" }}>
      <div style={{ marginBottom: 22, display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 16 }}>
        <div>
          <h1 style={{ margin: 0, fontSize: "var(--text-2xl)", fontWeight: 700, letterSpacing: "-0.02em", color: "var(--text-primary)" }}>{initialQuote ? "Edit Quote " + initialQuote.id : "New Quote"}</h1>
          <p style={{ margin: "4px 0 0", fontSize: "var(--text-sm)", color: "var(--text-muted)" }}>Real pricing from the One Day catalog — {cfg.catalog.length} door variants across {engine.collections(cfg.catalog).length} collections</p>
        </div>
        {initialQuote && <C.StatusBadge status={initialQuote.status}>{initialQuote.status}</C.StatusBadge>}
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 376px", gap: 24, alignItems: "start" }}>
        {/* Left: builder */}
        <div>
          <SectionCard icon="User" title="Customer">
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
              <div style={{ position: "relative" }}>
                <C.Input label="Name" value={cust.name} placeholder="Search or enter customer…" autoComplete="off"
                  onChange={(e) => { setCust((c) => ({ ...c, name: e.target.value })); setContactOpen(true); }}
                  onFocus={() => setContactOpen(true)}
                  onBlur={() => setTimeout(() => setContactOpen(false), 150)} />
                {contactOpen && contactMatches.length > 0 && (
                  <div style={{ position: "absolute", top: "100%", left: 0, right: 0, zIndex: 20, marginTop: 4, background: "#fff", border: "1px solid var(--border-default)", borderRadius: "var(--radius-md)", boxShadow: "var(--shadow-md)", overflow: "hidden" }}>
                    <div style={{ padding: "7px 12px", fontSize: "var(--text-2xs)", fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.08em", color: "var(--text-faint)", background: "var(--surface-sunken)" }}>Existing Contacts</div>
                    {contactMatches.map((c) => (
                      <button key={c.id} onMouseDown={(e) => { e.preventDefault(); pickContact(c); }} style={{ width: "100%", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, padding: "9px 12px", border: "none", borderTop: "1px solid var(--border-subtle)", background: "transparent", cursor: "pointer", textAlign: "left" }}
                        onMouseEnter={(e) => { e.currentTarget.style.background = "var(--surface-sunken)"; }} onMouseLeave={(e) => { e.currentTarget.style.background = "transparent"; }}>
                        <span style={{ fontSize: "var(--text-sm)", fontWeight: 600, color: "var(--text-primary)" }}>{c.first_name} {c.last_name}</span>
                        <span style={{ fontSize: "var(--text-xs)", color: "var(--text-muted)", fontVariantNumeric: "tabular-nums" }}>{c.phone}</span>
                      </button>
                    ))}
                  </div>
                )}
              </div>
              <C.Input label="Phone" value={cust.phone} placeholder="(210) 555-0000" onChange={setCustField("phone")} />
              <C.Input label="Email" value={cust.email} placeholder="name@example.com" onChange={setCustField("email")} />
              <C.Input label="Address" value={cust.address} placeholder="Street, City ST" onChange={setCustField("address")} />
            </div>
            {cust.name.trim() && (
              <div style={{ display: "flex", alignItems: "center", justifyContent: "flex-end", gap: 10, marginTop: 12, minHeight: 24 }}>
                {existsContact
                  ? <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: "var(--text-xs)", color: "var(--text-muted)" }}><Icon name="Contact" size={14} color="var(--text-faint)" />On file in contacts</span>
                  : contactSaved
                    ? <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: "var(--text-xs)", fontWeight: 600, color: "var(--status-sold-fg)" }}><Icon name="CheckCircle2" size={15} />Saved to contacts</span>
                    : <button onClick={createContact} style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "7px 14px", borderRadius: "var(--radius-full)", border: "1px solid var(--color-primary)", background: "var(--color-primary-soft)", color: "var(--color-primary-deep)", cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: "var(--text-xs)", fontWeight: 600 }}><Icon name="UserPlus" size={14} />Save as new contact</button>}
              </div>
            )}
          </SectionCard>

          <SectionCard icon="DoorClosed" title="Interior Doors" right={<C.Badge tone="moss">{quote.interiorDoorQty} doors</C.Badge>}>
            <div style={{ marginBottom: 16 }}>
              <DoorPicker catalog={cfg.catalog} onAdd={addDoor} />
            </div>
            <div>
              {interior.length === 0 && <p style={{ fontSize: "var(--text-sm)", color: "var(--text-muted)", textAlign: "center", padding: "12px 0" }}>No doors yet — add one above.</p>}
              {interior.map((it, idx) => {
                const m = engine.findDoor(cfg.catalog, it);
                const unit = m ? m.list : 0;
                return (
                  <div key={idx} style={{ display: "flex", alignItems: "center", gap: 12, padding: "11px 0", borderBottom: "1px solid var(--border-subtle)" }}>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: "var(--text-sm)", fontWeight: 600, color: "var(--text-primary)" }}>{it.style}</div>
                      <div style={{ fontSize: "var(--text-xs)", color: "var(--text-muted)", marginTop: 2 }}>{it.core} · {it.height} · {fmt(unit)}/door</div>
                    </div>
                    <div style={{ display: "flex", alignItems: "center", border: "1px solid var(--border-subtle)", borderRadius: "var(--radius-md)", overflow: "hidden" }}>
                      <button onClick={() => setQty(idx, it.qty - 1)} style={{ width: 28, height: 30, border: "none", background: "var(--surface-sunken)", cursor: "pointer", color: "var(--text-secondary)", fontSize: 15 }}>−</button>
                      <span style={{ width: 34, textAlign: "center", fontSize: "var(--text-sm)", fontWeight: 700, fontVariantNumeric: "tabular-nums" }}>{it.qty}</span>
                      <button onClick={() => setQty(idx, it.qty + 1)} style={{ width: 28, height: 30, border: "none", background: "var(--surface-sunken)", cursor: "pointer", color: "var(--text-secondary)", fontSize: 15 }}>+</button>
                    </div>
                    <div style={{ width: 88, textAlign: "right", fontSize: "var(--text-sm)", fontWeight: 700, color: "var(--text-primary)", fontVariantNumeric: "tabular-nums" }}>{fmt(unit * it.qty)}</div>
                    <button onClick={() => removeDoor(idx)} style={{ border: "none", background: "transparent", cursor: "pointer", color: "var(--text-faint)", display: "flex", padding: 4 }}><Icon name="Trash2" size={15} /></button>
                  </div>
                );
              })}
              {customItems.map((c, idx) => (
                <div key={"c" + idx} style={{ display: "flex", alignItems: "center", gap: 12, padding: "11px 0", borderBottom: "1px solid var(--border-subtle)" }}>
                  <input value={c.label} onChange={(e) => setCustom(idx, { label: e.target.value })} placeholder="Other item — e.g. closet shelving, trim, non-catalog door"
                    style={{ flex: 1, minWidth: 0, height: 34, padding: "0 12px", borderRadius: "var(--radius-md)", border: "1px solid var(--border-default)", background: "#fff", fontFamily: "var(--font-sans)", fontSize: "var(--text-sm)", fontWeight: 600, color: "var(--text-primary)", outline: "none" }} />
                  <div style={{ display: "flex", alignItems: "center", border: "1px solid var(--border-subtle)", borderRadius: "var(--radius-md)", overflow: "hidden" }}>
                    <button onClick={() => setCustom(idx, { qty: Math.max(1, (Number(c.qty) || 1) - 1) })} style={{ width: 28, height: 30, border: "none", background: "var(--surface-sunken)", cursor: "pointer", color: "var(--text-secondary)", fontSize: 15 }}>−</button>
                    <span style={{ width: 34, textAlign: "center", fontSize: "var(--text-sm)", fontWeight: 700, fontVariantNumeric: "tabular-nums" }}>{c.qty}</span>
                    <button onClick={() => setCustom(idx, { qty: (Number(c.qty) || 1) + 1 })} style={{ width: 28, height: 30, border: "none", background: "var(--surface-sunken)", cursor: "pointer", color: "var(--text-secondary)", fontSize: 15 }}>+</button>
                  </div>
                  <div style={{ position: "relative", width: 96 }}>
                    <span style={{ position: "absolute", left: 10, top: "50%", transform: "translateY(-50%)", fontSize: "var(--text-sm)", color: "var(--text-faint)", pointerEvents: "none" }}>$</span>
                    <input type="number" min="0" value={c.price} onChange={(e) => setCustom(idx, { price: Math.max(0, Number(e.target.value) || 0) })}
                      style={{ width: "100%", boxSizing: "border-box", height: 34, padding: "0 10px 0 22px", borderRadius: "var(--radius-md)", border: "1px solid var(--border-default)", background: "#fff", fontFamily: "var(--font-sans)", fontSize: "var(--text-sm)", fontWeight: 600, textAlign: "right", color: "var(--text-primary)", outline: "none", fontVariantNumeric: "tabular-nums" }} />
                  </div>
                  <div style={{ width: 88, textAlign: "right", fontSize: "var(--text-sm)", fontWeight: 700, color: "var(--text-primary)", fontVariantNumeric: "tabular-nums" }}>{fmt((Number(c.qty) || 0) * (Number(c.price) || 0))}</div>
                  <button onClick={() => removeCustom(idx)} style={{ border: "none", background: "transparent", cursor: "pointer", color: "var(--text-faint)", display: "flex", padding: 4 }}><Icon name="Trash2" size={15} /></button>
                </div>
              ))}
            </div>
            <button onClick={addCustom} style={{ marginTop: 14, display: "inline-flex", alignItems: "center", gap: 7, padding: "8px 14px", cursor: "pointer", borderRadius: "var(--radius-full)", fontFamily: "var(--font-sans)", fontSize: "var(--text-xs)", fontWeight: 600, border: "1.5px dashed var(--border-default)", background: "var(--surface-card)", color: "var(--text-secondary)" }}>
              <Icon name="Plus" size={14} />Add other item
            </button>
          </SectionCard>

          <SectionCard icon="Wrench" title="Job Options">
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "14px 28px" }}>
              {[
                ["paint", "Paint & finish", "$250 / door"],
                ["customColor", "Custom color", "$400 / door"],
                ["install", "Installation", "$300 / door"],
                ["hardwareInstall", "Hardware install", "$20 / door"],
                ["disposal", "Debris removal", "$5 / door"],
                ["freight", "Freight", "$50 / door"],
                ["measure3d", "3D laser measure", "$400 / job"],
                ["barn", "Barn-style install", "alt rate"],
              ].map(([k, label, sub]) => (
                <div key={k} style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                  <div><div style={{ fontSize: "var(--text-sm)", fontWeight: 600, color: "var(--text-primary)" }}>{label}</div><div style={{ fontSize: "var(--text-xs)", color: "var(--text-muted)" }}>{sub}</div></div>
                  <C.Switch checked={!!options[k]} onChange={() => toggleOpt(k)} />
                </div>
              ))}
            </div>

            {options.customColor && (
              <div style={{ marginTop: 16, padding: "16px 18px", borderRadius: "var(--radius-lg)", background: "var(--color-primary-soft)", border: "1px solid var(--color-primary-ring)" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap" }}>
                  <div>
                    <div style={{ fontSize: "var(--text-2xs)", fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.1em", color: "var(--text-faint)", marginBottom: 6 }}>Doors with custom color</div>
                    <div style={{ display: "flex", alignItems: "center", gap: 0, border: "1px solid var(--border-default)", borderRadius: "var(--radius-md)", overflow: "hidden", background: "#fff", width: "fit-content" }}>
                      <button onClick={() => setCopt("customColorQty", Math.max(1, (copts.customColorQty || doorCount) - 1))} style={{ width: 34, height: 36, border: "none", background: "transparent", cursor: "pointer", fontSize: 16, color: "var(--text-secondary)" }}>−</button>
                      <span style={{ minWidth: 36, textAlign: "center", fontSize: "var(--text-sm)", fontWeight: 700, fontVariantNumeric: "tabular-nums" }}>{copts.customColorQty || doorCount}</span>
                      <button onClick={() => setCopt("customColorQty", Math.min(doorCount, (copts.customColorQty || doorCount) + 1))} style={{ width: 34, height: 36, border: "none", background: "transparent", cursor: "pointer", fontSize: 16, color: "var(--text-secondary)" }}>+</button>
                    </div>
                    <div style={{ fontSize: "var(--text-2xs)", color: "var(--text-muted)", marginTop: 4 }}>of {doorCount} doors</div>
                  </div>
                  <div style={{ flex: 1, minWidth: 220 }}>
                    <div style={{ fontSize: "var(--text-2xs)", fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.1em", color: "var(--text-faint)", marginBottom: 6 }}>Sherwin-Williams color code</div>
                    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                      <span style={{ width: 40, height: 36, borderRadius: "var(--radius-md)", flexShrink: 0, border: "1px solid var(--border-default)", background: ccHex || "repeating-linear-gradient(45deg,#eee,#eee 5px,#f7f7f7 5px,#f7f7f7 10px)" }} title={ccName} />
                      <input value={copts.customColorCode || ""} onChange={(e) => applyCustomCode(e.target.value)} placeholder="e.g. SW 6258"
                        style={{ flex: 1, minWidth: 0, height: 36, padding: "0 12px", borderRadius: "var(--radius-md)", border: "1px solid var(--border-default)", background: "#fff", fontFamily: "var(--font-sans)", fontSize: "var(--text-sm)", color: "var(--text-primary)", outline: "none" }} />
                    </div>
                    {ccName && <div style={{ fontSize: "var(--text-2xs)", color: "var(--color-primary-deep)", fontWeight: 600, marginTop: 4 }}>{ccName}{ccHex ? "" : " — code not in chart (verify at measure)"}</div>}
                  </div>
                </div>
                <div style={{ fontSize: "var(--text-2xs)", fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.1em", color: "var(--text-faint)", margin: "14px 0 8px" }}>Sherwin-Williams chart · {window.SW_COLORS.length} colors</div>
                <div style={{ display: "flex", flexWrap: "wrap", gap: 8, maxHeight: 168, overflowY: "auto", paddingRight: 4 }}>
                  {window.SW_COLORS.filter((c) => !c.std).map((c) => { const on = (copts.customColorCode || "").replace(/[^0-9]/g, "") === c.code.replace(/[^0-9]/g, ""); return (
                    <button key={c.code + c.name} onClick={() => { setCopt("customColorCode", c.code); setCopt("customColorName", c.name); setCopt("customColorHex", c.hex); }} title={c.name + " · " + c.code}
                      style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "5px 11px 5px 6px", cursor: "pointer", borderRadius: "var(--radius-full)", fontSize: "var(--text-2xs)", fontWeight: 600, border: `1.5px solid ${on ? "var(--color-primary-deep)" : "var(--border-default)"}`, background: "#fff", color: on ? "var(--color-primary-deep)" : "var(--text-secondary)" }}>
                      <span style={{ width: 16, height: 16, borderRadius: "50%", background: c.hex, border: "1px solid rgba(0,0,0,0.18)" }} />{c.name}
                    </button>
                  ); })}
                </div>
              </div>
            )}
          </SectionCard>

          <SectionCard icon="BadgePercent" title="Discounts & Promotions">
            <div style={{ display: "flex", flexWrap: "wrap", gap: 10 }}>
              {cfg.discounts.map((d) => {
                const on = !!discounts[d.key];
                const amt = quote.discountAmounts[d.key] || 0;
                return (
                  <button key={d.key} onClick={() => toggleDisc(d.key)} title={d.basis}
                    style={{
                      display: "inline-flex", alignItems: "center", gap: 8, padding: "8px 14px", cursor: "pointer",
                      borderRadius: "var(--radius-full)", fontFamily: "var(--font-sans)", fontSize: "var(--text-xs)", fontWeight: 600,
                      border: `1.5px solid ${on ? "var(--color-primary-deep)" : "var(--border-default)"}`,
                      background: on ? "var(--color-primary-soft)" : "var(--surface-card)",
                      color: on ? "var(--color-primary-deep)" : "var(--text-secondary)",
                      transition: "all var(--duration-fast) var(--ease-standard)",
                    }}>
                    <Icon name={on ? "Check" : "Plus"} size={13} />
                    {d.label}
                    {on && amt > 0 && <span style={{ fontVariantNumeric: "tabular-nums", opacity: 0.85 }}>−{fmt(amt)}</span>}
                  </button>
                );
              })}
            </div>
          </SectionCard>

          <SectionCard icon="Paintbrush" title="Finishes & Hardware">
            <div style={{ fontSize: "var(--text-2xs)", fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.1em", color: "var(--text-faint)", marginBottom: 8 }}>Paint Color (factory finish)</div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginBottom: 18 }}>
              {[["Extra White", "SW 7006"], ["Pure White", "SW 7005"], ["Alabaster", "SW 7008"], ["Pearly White", "SW 7009"], ["Custom Color", "—"]].map(([n, c]) => {
                const on = copts.paintName === n;
                const sw = { "Extra White": "#F4F2EC", "Pure White": "#F7F5EF", "Alabaster": "#EDEAE0", "Pearly White": "#EEEBE2", "Custom Color": "#D6D1C3" }[n];
                return (
                  <button key={n} onClick={() => { setCopt("paintName", n); setCopt("paintCode", c); }}
                    style={{ display: "inline-flex", alignItems: "center", gap: 8, padding: "8px 14px", cursor: "pointer", borderRadius: "var(--radius-full)", fontFamily: "var(--font-sans)", fontSize: "var(--text-xs)", fontWeight: 600, border: `1.5px solid ${on ? "var(--color-primary-deep)" : "var(--border-default)"}`, background: on ? "var(--color-primary-soft)" : "var(--surface-card)", color: on ? "var(--color-primary-deep)" : "var(--text-secondary)" }}>
                    <span style={{ width: 16, height: 16, borderRadius: "50%", background: sw, border: "1px solid var(--border-default)" }} />
                    {n}<span style={{ opacity: 0.7 }}>{c !== "—" ? c : "· upcharge"}</span>
                    {on && <Icon name="Check" size={13} />}
                  </button>
                );
              })}
            </div>

            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }}>
              <div>
                <div style={{ fontSize: "var(--text-2xs)", fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.1em", color: "var(--text-faint)", marginBottom: 8 }}>Hardware Brand</div>
                <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
                  {["Emtek", "Yale", "Schlage", "Kwikset", "Other"].map((b) => { const on = copts.hardwareBrand === b; return (
                    <button key={b} onClick={() => setCopt("hardwareBrand", b)} style={{ padding: "7px 13px", borderRadius: "var(--radius-full)", cursor: "pointer", fontSize: "var(--text-xs)", fontWeight: 600, border: `1.5px solid ${on ? "var(--color-primary-deep)" : "var(--border-default)"}`, background: on ? "var(--color-primary-deep)" : "var(--surface-card)", color: on ? "#fff" : "var(--text-secondary)" }}>{b}</button>
                  ); })}
                </div>
                {copts.hardwareBrand === "Other" && (
                  <input value={copts.hardwareBrandOther || ""} onChange={(e) => setCopt("hardwareBrandOther", e.target.value)} placeholder="Enter brand name"
                    style={{ marginTop: 8, width: "100%", boxSizing: "border-box", height: 34, padding: "0 12px", borderRadius: "var(--radius-md)", border: "1px solid var(--border-default)", background: "#fff", fontFamily: "var(--font-sans)", fontSize: "var(--text-sm)", color: "var(--text-primary)", outline: "none" }} />
                )}
              </div>
              <div>
                <div style={{ fontSize: "var(--text-2xs)", fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.1em", color: "var(--text-faint)", marginBottom: 8 }}>Hardware Finish</div>
                <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
                  {["Matte Black", "Satin Nickel", "Polished Chrome", "Oil-Rubbed Bronze", "Aged Brass"].map((f) => { const on = copts.hardwareFinish === f; return (
                    <button key={f} onClick={() => setCopt("hardwareFinish", f)} style={{ padding: "7px 13px", borderRadius: "var(--radius-full)", cursor: "pointer", fontSize: "var(--text-xs)", fontWeight: 600, border: `1.5px solid ${on ? "var(--color-primary-deep)" : "var(--border-default)"}`, background: on ? "var(--color-primary-soft)" : "var(--surface-card)", color: on ? "var(--color-primary-deep)" : "var(--text-secondary)" }}>{f}</button>
                  ); })}
                </div>
              </div>
            </div>

            <div style={{ marginTop: 18, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }}>
              <div>
                <div style={{ fontSize: "var(--text-2xs)", fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.1em", color: "var(--text-faint)", marginBottom: 8 }}>Handle / Lever Style</div>
                <input value={copts.handle || ""} onChange={(e) => setCopt("handle", e.target.value)} placeholder="e.g. Helios Lever"
                  style={{ width: "100%", boxSizing: "border-box", height: 36, padding: "0 12px", borderRadius: "var(--radius-md)", border: "1px solid var(--border-default)", background: "#fff", fontFamily: "var(--font-sans)", fontSize: "var(--text-sm)", color: "var(--text-primary)", outline: "none" }} />
              </div>
              <div>
                <div style={{ fontSize: "var(--text-2xs)", fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.1em", color: "var(--text-faint)", marginBottom: 8 }}>Rosette / Backplate</div>
                <input value={copts.rosette || ""} onChange={(e) => setCopt("rosette", e.target.value)} placeholder="e.g. Round Rosette"
                  style={{ width: "100%", boxSizing: "border-box", height: 36, padding: "0 12px", borderRadius: "var(--radius-md)", border: "1px solid var(--border-default)", background: "#fff", fontFamily: "var(--font-sans)", fontSize: "var(--text-sm)", color: "var(--text-primary)", outline: "none" }} />
              </div>
            </div>

            <div style={{ marginTop: 18 }}>
              <div style={{ fontSize: "var(--text-2xs)", fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.1em", color: "var(--text-faint)", marginBottom: 8 }}>Handle Sets Provided By</div>
              <div style={{ display: "flex", gap: 8, maxWidth: 320 }}>
                {["Company", "Customer"].map((v) => { const on = copts.hardwareBy === v; return (
                  <button key={v} onClick={() => setCopt("hardwareBy", v)} style={{ flex: 1, padding: "9px", borderRadius: "var(--radius-lg)", cursor: "pointer", fontSize: "var(--text-sm)", fontWeight: 600, border: `2px solid ${on ? "var(--color-primary-deep)" : "var(--border-subtle)"}`, background: on ? "var(--color-primary-soft)" : "var(--surface-card)", color: on ? "var(--color-primary-deep)" : "var(--text-secondary)" }}>{v}</button>
                ); })}
              </div>
            </div>
          </SectionCard>

          <SectionCard icon="StickyNote" title="Notes for Contract">
            <p style={{ margin: "0 0 12px", fontSize: "var(--text-xs)", color: "var(--text-muted)" }}>These notes appear as a numbered clause ("Additional Notes &amp; Special Instructions") on the customer's contract.</p>
            <textarea value={notes} onChange={(e) => setNotes(e.target.value)} rows={4}
              placeholder="e.g. Leave existing bifold doors in the garage. Customer to confirm hallway paint at the 3D measure. Gate code 4417. Install crew to use side entrance."
              style={{ width: "100%", boxSizing: "border-box", padding: "12px 14px", borderRadius: "var(--radius-lg)", border: "1px solid var(--border-default)", background: "var(--input-bg)", fontFamily: "var(--font-sans)", fontSize: "var(--text-sm)", lineHeight: "var(--leading-normal)", color: "var(--text-primary)", resize: "vertical", outline: "none" }} />
          </SectionCard>
        </div>
        <div style={{ position: "sticky", top: 24, display: "flex", flexDirection: "column", gap: 16 }}>
          {/* Grand total hero */}
          <C.Card tone="forest" padding="lg">
            <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between" }}>
              <C.Stat value={fmtD(quote.grandTotal)} label="Grand Total (MSRP)" tone="forest" align="left" />
              <div style={{ padding: 8, borderRadius: "var(--radius-md)", background: "rgba(255,255,255,0.1)" }}>
                <Icon name="CircleDollarSign" size={20} color="rgba(255,255,255,0.7)" />
              </div>
            </div>
            <div style={{ marginTop: 16, paddingTop: 14, borderTop: "1px solid rgba(255,255,255,0.12)", display: "flex", alignItems: "flex-end", justifyContent: "space-between" }}>
              <div>
                <div style={{ fontSize: "var(--text-2xs)", textTransform: "uppercase", letterSpacing: "var(--tracking-widest)", color: "rgba(255,255,255,0.5)", fontWeight: 600 }}>Today's Investment</div>
                <div style={{ fontSize: "var(--text-2xl)", fontWeight: 700, color: "#fff", fontVariantNumeric: "tabular-nums", marginTop: 2 }}>{fmtD(quote.promotionalTotal)}</div>
              </div>
              {quote.totalDiscounts > 0 && <C.Badge tone="green" variant="solid">Save {fmt(quote.totalDiscounts)}</C.Badge>}
            </div>
          </C.Card>

          {/* Breakdown */}
          <C.Card padding="md">
            <C.Eyebrow size="2xs" style={{ marginBottom: 10 }}>Line Item Breakdown</C.Eyebrow>
            <div style={{ display: "flex", flexDirection: "column" }}>
              {[
                ["Interior doors", quote.breakdown.interiorSubtotal],
                ["Paint & finish", quote.breakdown.paintTotal],
                ["Custom color", quote.breakdown.customColorTotal],
                ["Other items", quote.breakdown.hardwareTotal],
                ["Installation", quote.breakdown.installTotal],
                ["Hardware install", quote.breakdown.hardwareInstallTotal],
                ["Debris removal", quote.breakdown.disposalTotal],
                ["3D measure", quote.breakdown.measure3dTotal],
                ["Freight", quote.breakdown.freightTotal],
              ].filter(([, v]) => v > 0).map(([k, v]) => (
                <div key={k} style={{ display: "flex", justifyContent: "space-between", padding: "5px 0" }}>
                  <span style={{ fontSize: "var(--text-xs)", color: "var(--text-muted)" }}>{k}</span>
                  <span style={{ fontSize: "var(--text-xs)", fontWeight: 600, color: "var(--text-primary)", fontVariantNumeric: "tabular-nums" }}>{fmt(v)}</span>
                </div>
              ))}
              {quote.totalDiscounts > 0 && (
                <div style={{ display: "flex", justifyContent: "space-between", padding: "5px 0" }}>
                  <span style={{ fontSize: "var(--text-xs)", color: "var(--status-lost-fg)" }}>Discounts</span>
                  <span style={{ fontSize: "var(--text-xs)", fontWeight: 600, color: "var(--status-lost-fg)", fontVariantNumeric: "tabular-nums" }}>−{fmt(quote.totalDiscounts)}</span>
                </div>
              )}
              <div style={{ display: "flex", justifyContent: "space-between", padding: "8px 0 0", marginTop: 4, borderTop: "1px solid var(--border-subtle)" }}>
                <span style={{ fontSize: "var(--text-xs)", color: "var(--text-muted)" }}>Tax (8.25% · materials)</span>
                <span style={{ fontSize: "var(--text-xs)", fontWeight: 600, color: "var(--text-primary)", fontVariantNumeric: "tabular-nums" }}>{fmt(quote.tax)}</span>
              </div>
            </div>
          </C.Card>

          {/* Commission band */}
          <C.Card padding="md" style={{ background: band.soft, border: `1px solid ${band.solid}33` }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 10 }}>
              <C.Eyebrow size="2xs" style={{ color: band.fg }}>Commission</C.Eyebrow>
              <span style={{ fontSize: "var(--text-2xs)", fontWeight: 700, padding: "3px 10px", borderRadius: "var(--radius-full)", background: band.solid, color: "#fff", textTransform: "uppercase", letterSpacing: "0.06em" }}>{quote.commissionTier.label} Band</span>
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: "var(--text-2xs)", color: "var(--text-muted)", marginBottom: 5 }}>
              <span>Margin</span><span style={{ fontWeight: 700, color: "var(--text-primary)" }}>{(quote.margin * 100).toFixed(1)}%</span>
            </div>
            <div style={{ height: 6, borderRadius: 3, background: "rgba(255,255,255,0.65)", overflow: "hidden" }}>
              <div style={{ width: Math.min(100, Math.max(0, quote.margin * 100)) + "%", height: "100%", background: band.solid, borderRadius: 3, transition: "width var(--duration-base) var(--ease-standard)" }} />
            </div>
            <div style={{ display: "flex", gap: 8, marginTop: 12 }}>
              <div style={{ flex: 1, textAlign: "center", background: "rgba(255,255,255,0.6)", borderRadius: "var(--radius-md)", padding: "8px 4px" }}>
                <div style={{ fontSize: "var(--text-2xs)", color: "var(--text-muted)" }}>Rate</div>
                <div style={{ fontSize: "var(--text-sm)", fontWeight: 700, color: "var(--text-primary)" }}>{(quote.commissionRate * 100).toFixed(1)}%</div>
              </div>
              <div style={{ flex: 1, textAlign: "center", background: "rgba(255,255,255,0.6)", borderRadius: "var(--radius-md)", padding: "8px 4px" }}>
                <div style={{ fontSize: "var(--text-2xs)", color: "var(--text-muted)" }}>Payout</div>
                <div style={{ fontSize: "var(--text-sm)", fontWeight: 700, color: "var(--text-primary)" }}>{fmt(quote.commissionAmount)}</div>
              </div>
            </div>
          </C.Card>

          {/* Payment options */}
          <C.Card padding="md">
            <C.Eyebrow size="2xs" style={{ marginBottom: 10 }}>Payment Options</C.Eyebrow>
            <div style={{ display: "flex", justifyContent: "space-between", padding: "6px 0", borderBottom: "1px solid var(--border-subtle)" }}>
              <span style={{ fontSize: "var(--text-xs)", color: "var(--text-muted)" }}>Cash · 50% deposit</span>
              <span style={{ fontSize: "var(--text-xs)", fontWeight: 700, color: "var(--text-primary)", fontVariantNumeric: "tabular-nums" }}>{fmtD(quote.deposit)}</span>
            </div>
            {quote.financing.map((p) => (
              <div key={p.id} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "7px 0", borderBottom: "1px solid var(--border-subtle)" }}>
                <span style={{ fontSize: "var(--text-xs)", color: "var(--text-muted)" }}>{p.label}</span>
                <span style={{ fontSize: "var(--text-sm)", fontWeight: 700, color: "var(--color-primary-deep)", fontVariantNumeric: "tabular-nums" }}>{fmt(p.monthly)}<span style={{ fontSize: "var(--text-2xs)", color: "var(--text-faint)", fontWeight: 400 }}>/mo</span></span>
              </div>
            ))}
          </C.Card>

          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            <C.Button variant="primary" fullWidth onClick={handleSave}><Icon name={saved ? "Check" : "Save"} size={16} />{saved ? "Saved" : (initialQuote ? "Update Quote" : "Save Quote")}</C.Button>
            <C.Button variant="deep" fullWidth onClick={handlePresent}><Icon name="MonitorPlay" size={16} />Present Pricing</C.Button>
          </div>
        </div>
      </div>
    </div>
  );
}

window.Calculator = Calculator;
