/* Contract — the signable Residential Door Replacement Agreement.
   A print-ready legal document (page 1 + Exhibits A–D) pre-filled from the
   customer record and the live quote (window.OneDayPricing). */

const K = window.Ds1Threshold_e046d3;

// ── Document primitives ──────────────────────────────────────────────────────
function Sheet({ exhibit, title, client, page, children }) {
  return (
    <div className="contract-sheet" style={{
      width: 816, maxWidth: "100%", margin: "0 auto 28px", background: "#fff",
      boxShadow: "var(--shadow-lg)", borderRadius: 3, padding: "56px 64px 40px", boxSizing: "border-box",
      color: "var(--text-primary)", fontSize: 12.5, lineHeight: 1.55,
    }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", borderBottom: "1px solid var(--border-subtle)", paddingBottom: 10, marginBottom: 22 }}>
        <span style={{ fontSize: 11, color: "var(--text-muted)" }}>Residential Door Replacement Agreement</span>
        <BrandMark height={26} variant="lockup" />
      </div>
      {exhibit && (
        <div style={{ marginBottom: 18 }}>
          <K.Eyebrow tone="primary" size="xs">{exhibit}</K.Eyebrow>
          <h2 style={{ margin: "4px 0 0", fontSize: 17, fontWeight: 700, letterSpacing: "-0.01em" }}>{title}</h2>
          {client && <p style={{ margin: "8px 0 0", fontSize: 12, color: "var(--text-secondary)" }}>Client Name: <strong>{client}</strong></p>}
        </div>
      )}
      {children}
      <div style={{ marginTop: 30, paddingTop: 12, borderTop: "1px solid var(--border-subtle)", display: "flex", justifyContent: "space-between", fontSize: 9.5, color: "var(--text-faint)" }}>
        <span>© 2025 One Day Doors &amp; Closets of San Antonio · www.OneDaySanAntonio.com</span>
        <span>{page}</span>
      </div>
    </div>
  );
}

function Clause({ n, title, children }) {
  return (
    <div style={{ marginBottom: 16 }}>
      <h3 style={{ margin: "0 0 5px", fontSize: 12.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.02em" }}>{n}. {title}</h3>
      <div style={{ color: "var(--text-secondary)" }}>{children}</div>
    </div>
  );
}

function Bullet({ children }) {
  return (
    <div style={{ display: "flex", gap: 8, marginBottom: 5 }}>
      <span style={{ color: "var(--color-primary)", flexShrink: 0, marginTop: 1 }}>●</span>
      <span style={{ color: "var(--text-secondary)" }}>{children}</span>
    </div>
  );
}

// A labelled fill-in field. Pre-filled values render in green ink.
function Field({ label, value, w = "auto", grow }) {
  return (
    <span style={{ display: "inline-flex", alignItems: "baseline", gap: 6, marginRight: 18, flex: grow ? 1 : "none" }}>
      <span style={{ fontSize: 12, color: "var(--text-secondary)", whiteSpace: "nowrap" }}>{label}</span>
      <span style={{
        minWidth: w, flex: grow ? 1 : "none", borderBottom: "1px solid var(--border-strong)",
        textAlign: "center", padding: "0 8px 1px", fontWeight: value ? 700 : 400,
        color: value ? "var(--color-primary-deep)" : "transparent", fontVariantNumeric: "tabular-nums",
      }}>{value || "\u00A0"}</span>
    </span>
  );
}

function Check({ label, on }) {
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 6, marginRight: 14 }}>
      <span style={{ width: 13, height: 13, border: "1.5px solid var(--border-strong)", borderRadius: 2, display: "inline-flex", alignItems: "center", justifyContent: "center", background: on ? "var(--color-primary-deep)" : "#fff" }}>
        {on && <Icon name="Check" size={10} color="#fff" />}
      </span>
      <span style={{ fontSize: 12, color: "var(--text-secondary)" }}>{label}</span>
    </span>
  );
}

function InitialBox() {
  return (
    <div style={{ marginTop: 20, display: "flex", justifyContent: "flex-end" }}>
      <span style={{ fontSize: 11, fontWeight: 600, color: "var(--text-muted)", textTransform: "uppercase", letterSpacing: "0.08em" }}>
        Customer Acknowledgement&nbsp;&nbsp;(Initial/Date) <span style={{ display: "inline-block", width: 130, borderBottom: "1px solid var(--border-strong)" }} />
      </span>
    </div>
  );
}

// ── The contract ─────────────────────────────────────────────────────────────
function Contract({ onClose, onRecord }) {
  const rawState = window.__OD_ACTIVE || window.DEFAULT_QUOTE_STATE || {};
  // Normalize: a quote always needs interior/exterior arrays so the document never crashes on a partial record.
  const state = Object.assign({}, rawState, { interior: Array.isArray(rawState.interior) ? rawState.interior : [], exterior: Array.isArray(rawState.exterior) ? rawState.exterior : [] });
  const cust = Object.assign({}, window.CUSTOMER, (state && state.customer) || {});
  let q;
  try { q = window.OneDayPricing.computeQuote(state, window.PRICING_CFG); }
  catch (e) { q = { lines: [], interiorDoorQty: 0, ladder: { today: 0, retail: 0, market: 0 } }; }
  q = q || {};
  if (!q.ladder) q.ladder = { today: 0, retail: 0, market: 0 };
  const interiorLines = (q.lines || []).filter((l) => l.kind === "interior");
  const partAt = (i) => { const set = []; interiorLines.forEach((l) => { const p = String(l.label).split("·").map((x) => x.trim()); if (p[i] && !set.includes(p[i])) set.push(p[i]); }); return set.length ? set : ["—"]; };
  const styles = partAt(0);
  const cores = partAt(1);
  const heights = partAt(2);

  // ── Editable contract options, persisted onto the active quote ──
  const saved = (state && state.contractOpts) || {};
  const [opts, setOpts] = React.useState({
    paintName: saved.paintName || "Pure White", paintCode: saved.paintCode || "SW 7005",
    hardwareBrand: saved.hardwareBrand || "Emtek", hardwareFinish: saved.hardwareFinish || "Matte Black",
    hardwareBy: saved.hardwareBy || "Company", notes: saved.notes || "",
    hardwareBrandOther: saved.hardwareBrandOther || "", handle: saved.handle || "", rosette: saved.rosette || "",
    customColorCode: saved.customColorCode || "", customColorName: saved.customColorName || "", customColorQty: saved.customColorQty || null,
  });
  const setOpt = (k, v) => setOpts((o) => { const n = { ...o, [k]: v }; if (state) state.contractOpts = n; return n; });
  const [sig, setSig] = React.useState(saved.sig || null);              // customer signature: {kind:'draw'|'type', dataUrl?, name}
  const [repSig, setRepSig] = React.useState(saved.repSig || null);     // rep / witness signature
  const [signedAt, setSignedAt] = React.useState(saved.signedAt || null);
  const [signerName, setSignerName] = React.useState(saved.signerName || null);
  const [showPad, setShowPad] = React.useState(false);
  const [showOpts, setShowOpts] = React.useState(false);
  const [emailed, setEmailed] = React.useState(false);
  const [recorded, setRecorded] = React.useState(false);               // dark-forest Saved-to-records hero
  const executed = !!sig;
  const sigImgOf = (s) => (s && s.kind === "draw" ? s.dataUrl : null);
  const commitSig = ({ customer, rep }) => {
    const ts = new Date().toLocaleDateString("en-US", { month: "short", day: "2-digit", year: "numeric" });
    setSig(customer); setRepSig(rep || null); setSignedAt(ts); setSignerName(customer.name);
    if (state) state.contractOpts = { ...opts, sig: customer, repSig: rep || null, signedAt: ts, signerName: customer.name };
    setShowPad(false);
    // Save to records (Miney wires the Supabase persist behind onRecord).
    const rec = onRecord && onRecord({ signer_name: customer.name, signed_at: new Date().toISOString(), total: q.ladder.today, customer: cust.name });
    setRecorded(true);
  };

  const PAINTS = [["Extra White", "SW 7006"], ["Pure White", "SW 7005"], ["Alabaster", "SW 7008"], ["Pearly White", "SW 7009"], ["Snowbound", "SW 7004"], ["Custom Color", "—"]];
  const HW_BRANDS = ["Emtek", "Yale", "Schlage", "Kwikset", "Other"];
  const HW_FINISHES = ["Matte Black", "Satin Nickel", "Polished Chrome", "Oil-Rubbed Bronze", "Aged Brass"];

  return (
    <div style={{ position: "absolute", inset: 0, zIndex: 60, background: "var(--surface-sunken)", display: "flex", flexDirection: "column" }}>
      {/* Toolbar */}
      <div className="contract-toolbar" style={{ background: "var(--surface-card)", borderBottom: "1px solid var(--border-subtle)", padding: "12px 22px", display: "flex", alignItems: "center", justifyContent: "space-between", flexShrink: 0, zIndex: 2 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
          <button onClick={onClose} style={{ width: 34, height: 34, borderRadius: "var(--radius-md)", border: "1px solid var(--border-subtle)", background: "#fff", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--text-muted)" }}>
            <Icon name="ArrowLeft" size={16} />
          </button>
          <div>
            <div style={{ fontSize: "var(--text-sm)", fontWeight: 700, color: "var(--text-primary)" }}>Residential Door Replacement Agreement</div>
            <div style={{ fontSize: "var(--text-xs)", color: "var(--text-muted)" }}>{cust.name} · Invoice {cust.invoice} · {fmtD(q.ladder.today)}</div>
          </div>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          {recorded || executed
            ? <K.Badge tone="sold" style={{ background: "var(--status-sold-bg)", color: "var(--status-sold-fg)" }}><Icon name="Lock" size={12} />Signed · Locked Record</K.Badge>
            : <K.Badge tone="pending" style={{ background: "var(--status-pending-bg)", color: "var(--status-pending-fg)" }}>Awaiting Signature</K.Badge>}
          <K.Button variant="outline" size="md" onClick={() => setShowOpts(true)}><Icon name="SlidersHorizontal" size={15} />Options</K.Button>
          <K.Button variant="outline" size="md" onClick={() => window.print()}><Icon name="Printer" size={15} />Print</K.Button>
          {executed
            ? <K.Button variant="deep" size="md" onClick={() => { setEmailed(true); setTimeout(() => setEmailed(false), 3200); }}><Icon name="Mail" size={15} />Email Executed Contract</K.Button>
            : <K.Button variant="deep" size="md" onClick={() => setShowPad(true)}><Icon name="PenLine" size={15} />Sign on Device</K.Button>}
        </div>
      </div>

      {emailed && (
        <div style={{ position: "absolute", top: 70, right: 22, zIndex: 80, background: "var(--text-primary)", color: "#fff", padding: "12px 18px", borderRadius: "var(--radius-lg)", boxShadow: "var(--shadow-lg)", display: "flex", alignItems: "center", gap: 10, fontSize: "var(--text-sm)", fontWeight: 600 }}>
          <Icon name="MailCheck" size={17} color="var(--od-rosewood)" />Executed contract emailed to {cust.email}
        </div>
      )}

      {showPad && <SigningModal name={cust.name} repName={cust.rep} onCancel={() => setShowPad(false)} onSave={commitSig} K={K} />}
      {showOpts && <OptionsPanel opts={opts} setOpt={setOpt} paints={PAINTS} brands={HW_BRANDS} finishes={HW_FINISHES} onClose={() => setShowOpts(false)} K={K} />}
      {recorded && <SavedToRecords cust={cust} total={q.ladder.today} signer={signerName} onClose={() => setRecorded(false)} onViewRecords={() => { setRecorded(false); onClose && onClose("records"); }} K={K} />}

      {/* Document body */}
      <div className="contract-scroll" style={{ flex: 1, overflow: "auto", padding: "32px 20px" }}>

        {/* PAGE 1 — AGREEMENT */}
        <Sheet page="1">
          <h1 style={{ margin: "0 0 6px", fontSize: 19, fontWeight: 800, letterSpacing: "-0.01em" }}>Residential Door Replacement Agreement</h1>
          <p style={{ margin: "0 0 18px", color: "var(--text-secondary)" }}>
            (“Agreement”) This Agreement is made by and between <strong>One Day Doors &amp; Closets of San Antonio</strong> (hereinafter “Company,” “we,” “us,” or “our”) and the undersigned customer (hereinafter “Customer,” “you,” or “your”).
          </p>

          <Clause n="1" title="Parties & Contact Information">
            <div style={{ display: "flex", flexWrap: "wrap", rowGap: 12, marginTop: 8 }}>
              <Field label="Customer Name:" value={cust.name} w={220} />
              <Field label="Project Address:" value={cust.address} w={260} />
              <Field label="3D Measure Date:" value="08 / 14" w={70} />
              <Field label="Email:" value={cust.email} w={170} />
              <Field label="Phone:" value={cust.phone} w={130} />
              <Field label="Invoice #" value={cust.invoice} w={90} />
            </div>
          </Clause>

          <Clause n="2" title="Special Order & Cancellation">
            All doors, hardware, and related components are special-order, custom-manufactured items. Doors are typically ordered within 24 hours of Customer’s execution of this Agreement. Once ordered, materials are non-returnable and non-refundable. Door styles cannot be changed after the order is placed. All approved post-order changes may result in additional cost. If any product becomes unavailable, Company may substitute with an item of equal or greater quality, subject to customer approval.
          </Clause>

          <Clause n="3" title="Timeline & Scheduling">
            <Bullet>Installation is estimated to occur within 90–150 days from digital measurement.</Bullet>
            <Bullet>Rescheduling within 14 days of either the Digital Measure or Install date may delay your project by up to 6 additional weeks.</Bullet>
            <Bullet>Flooring must be fully installed prior to Digital Measure. Failure to meet this condition may result in a schedule delay.</Bullet>
            <Bullet>Customer agrees to a final walkthrough on the day of installation. Any punch list items must be submitted in writing within 3 business days. After that time, the project shall be deemed complete.</Bullet>
          </Clause>

          <Clause n="4" title="Site Access & Customer Responsibilities">
            Customer shall: (1) Ensure all work areas are accessible and clear of furniture and valuables. (2) Secure all pets and ensure children are kept away from work areas. (3) Provide parking access for delivery/installation teams. (4) Prevent overlap with other contractors during install days. Company shall not be liable for damages to unsecured personal property, unattended pets, or third-party interference, nor for concealed or hazardous conditions not visible at the time of initial inspection.
          </Clause>

          <Clause n="5" title="Paint, Gaps & Trim">
            <Bullet>Doors are factory-painted on four sides. Tops and bottoms are unpainted unless Exhibit A specifies otherwise.</Bullet>
            <Bullet>Fascia, trim, and closet bumpers are primed only, not finished.</Bullet>
            <Bullet>Floor-to-door gaps may range from ½″ to 1¼″, depending on the floor level and header framing.</Bullet>
            <Bullet>Bypass doors will overlap between ½″ and 4″ and have visible track and fascia.</Bullet>
          </Clause>

          <Clause n="6" title="Warranty Summary">
            This Agreement incorporates the Limited Lifetime Warranty described in Exhibit C, which covers door slabs &amp; finish for the life of ownership and installation labor for three (3) years.
          </Clause>

          <Clause n="7" title="Limitation of Liability">
            Company’s liability is limited to repair or replacement of defective goods. No liability is assumed for incidental or consequential damages. Company shall not be liable for any delay or failure in performance resulting from acts of God, weather events, supply chain disruption, labor shortages, or other causes beyond its reasonable control.
          </Clause>

          <Clause n="8" title="Governing Law & Dispute Resolution">
            This Agreement shall be governed by the laws of the State of Texas. All claims shall be brought in the courts of Bexar County, TX.
          </Clause>

          <Clause n="9" title="Entire Agreement">
            This Agreement, together with all attached exhibits, represents the full understanding between the parties and supersedes all prior agreements or representations.
          </Clause>

          {opts.notes && opts.notes.trim() && (
            <Clause n="10" title="Additional Notes & Special Instructions">
              <div style={{ whiteSpace: "pre-wrap", color: "var(--text-secondary)" }}>{opts.notes}</div>
            </Clause>
          )}

          {/* Signatures */}
          <div style={{ marginTop: 24, padding: "20px 22px", background: "var(--color-primary-soft)", border: "1px solid var(--color-primary-ring)", borderRadius: "var(--radius-lg)" }}>
            <K.Eyebrow tone="primary" style={{ marginBottom: 16 }}>Acceptance &amp; Signatures</K.Eyebrow>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "22px 32px" }}>
              <SignLine role="Customer Signature" name={cust.name} sigImg={sigImgOf(sig)} typed={sig && sig.kind === "type" ? sig.name : null} signedAt={signedAt} onSign={() => setShowPad(true)} />
              <SignLine role="Company Rep Signature" name={cust.rep} sigImg={sigImgOf(repSig)} typed={repSig && repSig.kind === "type" ? repSig.name : null} signedAt={repSig ? signedAt : null} />
            </div>
            <div style={{ marginTop: 16, display: "flex", alignItems: "baseline", justifyContent: "space-between" }}>
              <span style={{ fontSize: 11, color: "var(--text-muted)" }}>Total Agreement Value (Today’s Investment)</span>
              <span style={{ fontSize: 20, fontWeight: 800, color: "var(--color-primary-deep)", fontVariantNumeric: "tabular-nums" }}>{fmtD(q.ladder.today)}</span>
            </div>
          </div>
        </Sheet>

        {/* EXHIBIT A — PRODUCT SPEC */}
        <Sheet exhibit="Exhibit A" title="Product Specification Sheet" client={cust.name} page="2">
          <h3 style={{ margin: "0 0 10px", fontSize: 12.5, fontWeight: 700 }}>1. Project Specification Form</h3>
          <p style={{ margin: "0 0 12px", color: "var(--text-muted)", fontSize: 11.5 }}>Auto-completed from the approved quote. Verify at the 3D Measure visit.</p>
          <div style={{ display: "flex", flexWrap: "wrap", rowGap: 12, marginBottom: 8 }}>
            <Check label="Installation: Yes" on /><Check label="No" />
            <Check label="Delivery: Yes" on /><Check label="No" />
          </div>
          <div style={{ display: "flex", flexWrap: "wrap", rowGap: 14, marginTop: 6 }}>
            <Field label="Quantity of Doors:" value={String(q.interiorDoorQty)} w={70} />
            <Field label="Door Style(s):" value={styles.join(", ")} w={260} />
            <Field label="Core Type(s):" value={cores.join(", ")} w={120} />
            <Field label="Height(s):" value={heights.join(", ")} w={90} />
          </div>
          <div style={{ display: "flex", flexWrap: "wrap", rowGap: 14, marginTop: 14 }}>
            <span style={{ fontSize: 12, color: "var(--text-secondary)", marginRight: 8 }}>Hinge Radius:</span>
            <Check label='1/4"' /><Check label='5/8"' on /><Check label="Square" />
            <Field label="Paint Color (SW):" value={opts.paintName + (opts.paintCode !== "—" ? " " + opts.paintCode : "")} w={170} />
            <Field label="Backset (std 2⅜″):" value="" w={90} />
          </div>

          {/* Live line-item table from the quote */}
          <div style={{ marginTop: 22 }}>
            <K.Eyebrow size="2xs" style={{ marginBottom: 8 }}>Approved Line Items</K.Eyebrow>
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 11.5 }}>
              <thead>
                <tr style={{ background: "var(--surface-sunken)" }}>
                  {["Door Style", "Core", "Height", "Qty", "Unit", "Total"].map((h, i) => (
                    <th key={h} style={{ textAlign: i > 2 ? "right" : "left", padding: "7px 10px", fontWeight: 700, color: "var(--text-secondary)", borderBottom: "1px solid var(--border-default)" }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {state.interior.map((it, i) => {
                  const m = window.OneDayPricing.findDoor(window.PRICING_CFG.catalog, it);
                  const unit = m ? m.list : 0;
                  return (
                    <tr key={i}>
                      <td style={{ padding: "7px 10px", borderBottom: "1px solid var(--border-subtle)" }}>{it.style}</td>
                      <td style={{ padding: "7px 10px", borderBottom: "1px solid var(--border-subtle)" }}>{it.core}</td>
                      <td style={{ padding: "7px 10px", borderBottom: "1px solid var(--border-subtle)" }}>{it.height}</td>
                      <td style={{ padding: "7px 10px", textAlign: "right", borderBottom: "1px solid var(--border-subtle)", fontVariantNumeric: "tabular-nums" }}>{it.qty}</td>
                      <td style={{ padding: "7px 10px", textAlign: "right", borderBottom: "1px solid var(--border-subtle)", fontVariantNumeric: "tabular-nums" }}>{fmt(unit)}</td>
                      <td style={{ padding: "7px 10px", textAlign: "right", borderBottom: "1px solid var(--border-subtle)", fontWeight: 700, fontVariantNumeric: "tabular-nums" }}>{fmt(unit * it.qty)}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>

          <h3 style={{ margin: "22px 0 8px", fontSize: 12.5, fontWeight: 700 }}>2. Hardware Summary</h3>
          <div style={{ display: "flex", flexWrap: "wrap", rowGap: 10 }}>
            <span style={{ fontSize: 12, color: "var(--text-secondary)", marginRight: 8 }}>Handle Sets Provided By:</span>
            <Check label="Company" on={opts.hardwareBy === "Company"} /><Check label="Customer" on={opts.hardwareBy === "Customer"} />
            <Field label="Standard Finish:" value={opts.hardwareFinish} w={140} />
            <span style={{ fontSize: 12, color: "var(--text-secondary)", marginRight: 8 }}>Brand:</span>
            <Check label={opts.hardwareBrand === "Other" && opts.hardwareBrandOther ? opts.hardwareBrandOther : opts.hardwareBrand} on />
          </div>
          <div style={{ display: "flex", flexWrap: "wrap", rowGap: 12, marginTop: 12 }}>
            <Field label="Handle / Lever:" value={opts.handle || "Standard"} w={170} />
            <Field label="Rosette / Backplate:" value={opts.rosette || "Standard"} w={170} />
          </div>
          <InitialBox />
        </Sheet>

        {/* EXHIBIT B — PAINT, GAP & PRODUCTION POLICY */}
        <Sheet exhibit="Exhibit B" title="Paint, Gap & Production Policy" client={cust.name} page="3">
          <h3 style={{ margin: "0 0 8px", fontSize: 12.5, fontWeight: 700 }}>1. Paint Selection &amp; Finish</h3>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 10, marginBottom: 10 }}>
            {[["Extra White", "SW 7006"], ["Pure White", "SW 7005"], ["Alabaster", "SW 7008"], ["Pearly White", "SW 7009"]].map(([n, c]) => { const on = opts.paintName === n; return (
              <span key={c} style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "6px 12px", borderRadius: "var(--radius-full)", border: `1.5px solid ${on ? "var(--color-primary-deep)" : "var(--border-default)"}`, background: on ? "var(--color-primary-soft)" : "#fff", fontSize: 11.5, fontWeight: 600, color: on ? "var(--color-primary-deep)" : "var(--text-secondary)" }}>
                <span style={{ width: 14, height: 14, borderRadius: "50%", background: "#fafafa", border: "1px solid var(--border-default)" }} />{n} · {c}{on && <Icon name="Check" size={12} />}
              </span>
            ); })}
          </div>
          <p style={{ margin: "0 0 6px", color: "var(--text-secondary)", fontSize: 11.5 }}>Selecting a factory-standard color qualifies the finish for Company’s proprietary oven-cured process and the finish warranty (Exhibit C). Custom colors are finished by an alternate method, may extend lead-time, incur an additional charge, and are excluded from the finish warranty. Customer shall finalize the paint color no later than the Digital Measure Visit. Application of painter’s tape, decals, or adhesive hooks voids the finish warranty. Matching trim/touch-up paint is available under Sherwin-Williams Account # 9396-0971-5 at a 20% discount.</p>

          <h3 style={{ margin: "16px 0 6px", fontSize: 12.5, fontWeight: 700 }}>2. Floor Gaps &amp; Provisions</h3>
          <Bullet>Clearance between the door bottom and finished floor may range from 0.50″ to 1.25″. Such range is customary and acceptable.</Bullet>
          <Bullet>Openings exceeding 80″ may require oversize doors — a <strong>$250 upcharge per door</strong> applies, or standard doors may be installed with a larger floor gap.</Bullet>
          <Bullet>Standard overlap for bypass doors varies from 0.50″ to 4.00″; fascia boards and roller guides remain visible.</Bullet>
          <Bullet>Company is not responsible for interference between new doors and pre-existing drawers, shelves, or fixtures.</Bullet>

          <h3 style={{ margin: "16px 0 8px", fontSize: 12.5, fontWeight: 700 }}>3. Eight-Step Production Timeline</h3>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "8px 18px" }}>
            {[
              "Order Confirmation — contract executed; items classified special order.",
              "Material Receipt — raw materials arrive (≈ 48–72 hrs).",
              "Digital Measure — performed on-site; flooring must be installed.",
              "CNC Milling — doors cut to ± 0.001″ tolerance.",
              "Prep & Priming — sanding and primer (≈ 80% of finishing labor).",
              "Final Color Coats — oven-cured for durability.",
              "Packaging & Shipment — packed and transported to site.",
              "Installation — typical whole-home install completed in one day.",
            ].map((t, i) => (
              <div key={i} style={{ display: "flex", gap: 9, alignItems: "flex-start" }}>
                <span style={{ flexShrink: 0, width: 20, height: 20, borderRadius: "50%", background: "var(--color-primary-deep)", color: "#fff", fontSize: 11, fontWeight: 700, display: "flex", alignItems: "center", justifyContent: "center" }}>{i + 1}</span>
                <span style={{ fontSize: 11.5, color: "var(--text-secondary)" }}>{t}</span>
              </div>
            ))}
          </div>
          <p style={{ margin: "16px 0 0", fontSize: 11, color: "var(--text-muted)" }}><strong>Pocket &amp; Specialty Doors:</strong> Pocket door tracks, frames, rollers, and associated hardware are excluded from all warranties. Accessing or servicing pocket-door hardware may require removal of drywall or surrounding finishes and may result in surface damage, for which Company bears no restoration responsibility.</p>
          <InitialBox />
        </Sheet>

        {/* EXHIBIT C — WARRANTY */}
        <Sheet exhibit="Exhibit C" title="Limited Lifetime Warranty & Care Sheet" client={cust.name} page="4">
          <h3 style={{ margin: "0 0 6px", fontSize: 12.5, fontWeight: 700 }}>1. Warranty Coverage</h3>
          <Bullet><strong>Door Slabs &amp; Factory Finish</strong> — free from defects in materials and workmanship for as long as the Customer owns and occupies the residence where the products were originally installed.</Bullet>
          <Bullet><strong>Workmanship / Labor</strong> — installation workmanship is warranted for three (3) years from the date of installation.</Bullet>

          <h3 style={{ margin: "16px 0 6px", fontSize: 12.5, fontWeight: 700 }}>2. Exclusions &amp; Limitations</h3>
          <p style={{ margin: "0 0 6px", color: "var(--text-secondary)", fontSize: 11.5 }}>This Warranty does not cover defects or damage arising from: improper handling, misuse, or neglect; excessive moisture, humidity, or direct sunlight; application of tape/decals/adhesive hooks; removal or reinstallation by any party other than Company; custom-color finishes; customer-supplied hardware; pocket-door components; normal wear, wood grain, micro-texturing, or color variation; or acts of God. Company’s sole obligation is, at its option, to repair or replace the defective product. To the fullest extent permitted by Texas law, Company shall not be liable for incidental, consequential, special, indirect, or punitive damages.</p>

          <h3 style={{ margin: "16px 0 6px", fontSize: 12.5, fontWeight: 700 }}>3. Customer Care &amp; Maintenance</h3>
          <Bullet>Clean doors with a soft cloth dampened with mild soap and water; avoid abrasive cleaners or solvents.</Bullet>
          <Bullet>Keep relative humidity between 30% and 60% and avoid prolonged contact with water.</Bullet>
          <Bullet>Tighten hardware screws annually and lubricate hinges as needed with a non-petroleum lubricant.</Bullet>

          <h3 style={{ margin: "16px 0 6px", fontSize: 12.5, fontWeight: 700 }}>4. Claim Procedure &amp; Transferability</h3>
          <p style={{ margin: 0, color: "var(--text-secondary)", fontSize: 11.5 }}>Customer must provide written notice of the alleged defect within thirty (30) days of discovery and within the applicable warranty period, including proof of purchase and photographs. Company reserves the right to inspect the product in situ before authorizing any remedy. This Warranty is non-transferable and extends only to the original purchasing homeowner named on the Agreement.</p>
          <InitialBox />
        </Sheet>

        {/* EXHIBIT D — PHOTO RELEASE */}
        <Sheet exhibit="Exhibit D" title="Photo & Testimonial Release" client={cust.name} page="5">
          <Clause n="A" title="Consent">Releasor grants One Day Doors &amp; Closets of San Antonio the irrevocable right to photograph and/or record video of the doors and closets installed at the Project Address, and to use such images, recordings, and accompanying testimonials for advertising, marketing, and promotional purposes, in any medium now known or later developed.</Clause>
          <Clause n="B" title="Privacy">Company shall not publish Releasor’s last name, street address, or any personally identifying information without separate written consent.</Clause>
          <Clause n="C" title="Compensation & Ownership">No compensation, royalty, or further consideration will be paid for the rights granted herein. All photographs, recordings, and derivatives remain the sole property of Company.</Clause>
          <Clause n="D" title="Release & Governing Law">Releasor releases Company, its agents, employees, and assignees from any claims arising out of the use of said images or testimonials, including claims for defamation or invasion of privacy. This Release shall be governed by the laws of the State of Texas.</Clause>
          <div style={{ marginTop: 18, padding: "18px 20px", border: "1px solid var(--border-subtle)", borderRadius: "var(--radius-lg)" }}>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "20px 32px" }}>
              <SignLine role="Releasor Signature" name={cust.name} />
              <span style={{ display: "flex", alignItems: "flex-end" }}><Field label="Date:" value="" w={120} /></span>
            </div>
          </div>
          <InitialBox />
        </Sheet>

        <div style={{ height: 8 }} />
      </div>
    </div>
  );
}

// Signature line with optional captured-signature image, typed (Georgia) name, or script-font fallback.
function SignLine({ role, name, sigImg, typed, signedAt, signed, onSign }) {
  const isSigned = !!sigImg || !!typed || signed;
  return (
    <div>
      <div onClick={!isSigned && onSign ? onSign : undefined} style={{ height: 44, borderBottom: "1px solid var(--text-primary)", display: "flex", alignItems: "flex-end", justifyContent: (sigImg || typed) ? "flex-start" : "center", paddingBottom: 2, cursor: !isSigned && onSign ? "pointer" : "default" }}>
        {sigImg
          ? <img src={sigImg} alt="signature" style={{ height: 40, objectFit: "contain" }} />
          : typed
            ? <span style={{ fontFamily: "Georgia, 'Times New Roman', serif", fontStyle: "italic", fontSize: 26, color: "var(--text-primary)", lineHeight: 1.1 }}>{typed}</span>
            : signed
              ? <span style={{ fontFamily: "Georgia, 'Times New Roman', serif", fontStyle: "italic", fontSize: 22, color: "var(--text-primary)" }}>{name}</span>
              : onSign
                ? <span style={{ marginBottom: 8, display: "inline-flex", alignItems: "center", gap: 6, fontSize: 11.5, fontWeight: 700, color: "var(--color-primary-deep)" }}><Icon name="PenLine" size={13} />Tap to sign on device</span>
                : null}
      </div>
      <div style={{ display: "flex", justifyContent: "space-between", marginTop: 5 }}>
        <span style={{ fontSize: 11, color: "var(--text-muted)" }}>{role}</span>
        <span style={{ fontSize: 11, color: "var(--text-muted)" }}>{isSigned ? (signedAt || "Aug 14, 2026") : "Date"}</span>
      </div>
      <div style={{ fontSize: 11, color: "var(--text-faint)", marginTop: 3 }}>Print: {name}</div>
    </div>
  );
}

// (Signing handled by SigningModal — typed/draw + rep witness.)

// Slide-over panel to edit paint color, hardware, and contract notes.
function OptionsPanel({ opts, setOpt, paints, brands, finishes, onClose, K }) {
  const swatch = (n) => ({ "Extra White": "#F4F2EC", "Pure White": "#F7F5EF", "Alabaster": "#EDEAE0", "Pearly White": "#EEEBE2", "Snowbound": "#EFEDE7", "Custom Color": "#D6D1C3" }[n] || "#EEE");
  const Lbl = ({ children }) => <div style={{ fontSize: "var(--text-2xs)", fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.1em", color: "var(--text-faint)", margin: "18px 0 8px" }}>{children}</div>;
  return (
    <div style={{ position: "absolute", inset: 0, zIndex: 85, background: "rgba(28,26,24,0.4)", display: "flex", justifyContent: "flex-end" }} onClick={onClose}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: "min(420px, 100%)", height: "100%", background: "#fff", boxShadow: "var(--shadow-lg)", display: "flex", flexDirection: "column" }}>
        <div style={{ padding: "18px 22px", borderBottom: "1px solid var(--border-subtle)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <div><K.Eyebrow tone="primary">Contract Options</K.Eyebrow><div style={{ fontSize: "var(--text-sm)", color: "var(--text-muted)", marginTop: 3 }}>Paint, hardware &amp; notes flow into the document.</div></div>
          <button onClick={onClose} style={{ width: 32, height: 32, borderRadius: "var(--radius-md)", border: "1px solid var(--border-subtle)", background: "#fff", cursor: "pointer", color: "var(--text-muted)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="X" size={15} /></button>
        </div>
        <div style={{ flex: 1, overflow: "auto", padding: "4px 22px 24px" }}>
          <Lbl>Paint Color (factory finish)</Lbl>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {paints.map(([n, c]) => { const on = opts.paintName === n; return (
              <button key={n} onClick={() => { setOpt("paintName", n); setOpt("paintCode", c); }} style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 12px", borderRadius: "var(--radius-lg)", cursor: "pointer", textAlign: "left", border: `2px solid ${on ? "var(--color-primary-deep)" : "var(--border-subtle)"}`, background: on ? "var(--color-primary-soft)" : "#fff" }}>
                <span style={{ width: 26, height: 26, borderRadius: "50%", background: swatch(n), border: "1px solid var(--border-default)", flexShrink: 0 }} />
                <span style={{ flex: 1 }}><span style={{ fontSize: "var(--text-sm)", fontWeight: 600, color: "var(--text-primary)" }}>{n}</span> <span style={{ fontSize: "var(--text-xs)", color: "var(--text-muted)" }}>{c !== "—" ? c : "(upcharge · not warranted)"}</span></span>
                {on && <Icon name="Check" size={16} color="var(--color-primary-deep)" />}
              </button>
            ); })}
          </div>

          <Lbl>Hardware Brand</Lbl>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
            {brands.map((b) => { const on = opts.hardwareBrand === b; return (
              <button key={b} onClick={() => setOpt("hardwareBrand", b)} style={{ padding: "8px 14px", 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)" : "#fff", color: on ? "#fff" : "var(--text-secondary)" }}>{b}</button>
            ); })}
          </div>

          <Lbl>Hardware Finish</Lbl>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
            {finishes.map((f) => { const on = opts.hardwareFinish === f; return (
              <button key={f} onClick={() => setOpt("hardwareFinish", f)} style={{ padding: "8px 14px", 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)" : "#fff", color: on ? "var(--color-primary-deep)" : "var(--text-secondary)" }}>{f}</button>
            ); })}
          </div>

          <Lbl>Handle Sets Provided By</Lbl>
          <div style={{ display: "flex", gap: 8 }}>
            {["Company", "Customer"].map((v) => { const on = opts.hardwareBy === v; return (
              <button key={v} onClick={() => setOpt("hardwareBy", v)} style={{ flex: 1, padding: "10px", 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)" : "#fff", color: on ? "var(--color-primary-deep)" : "var(--text-secondary)" }}>{v}</button>
            ); })}
          </div>

          <Lbl>Notes &amp; Special Instructions</Lbl>
          <textarea value={opts.notes} onChange={(e) => setOpt("notes", e.target.value)} placeholder="e.g. Leave existing bifold in the garage. Customer to confirm hallway paint at measure. Gate code 4417." rows={5}
            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)", color: "var(--text-primary)", resize: "vertical", outline: "none" }} />
          <div style={{ fontSize: 11, color: "var(--text-faint)", marginTop: 6 }}>Appears as a numbered clause in the executed contract.</div>
        </div>
        <div style={{ padding: "16px 22px", borderTop: "1px solid var(--border-subtle)" }}>
          <K.Button variant="deep" size="md" fullWidth onClick={onClose}><Icon name="Check" size={15} />Done</K.Button>
        </div>
      </div>
    </div>
  );
}

// ── On-device signing: typed (Georgia) or drawn, customer + rep/witness ──────
function DrawPad({ inkRef }) {
  const canvasRef = React.useRef(null);
  const drawing = React.useRef(false);
  React.useEffect(() => {
    const c = canvasRef.current; if (!c) return;
    const ratio = window.devicePixelRatio || 1;
    c.width = c.offsetWidth * ratio; c.height = c.offsetHeight * ratio;
    const ctx = c.getContext("2d"); ctx.scale(ratio, ratio);
    ctx.lineWidth = 2.4; ctx.lineCap = "round"; ctx.lineJoin = "round"; ctx.strokeStyle = "#19332F";
    inkRef.current = { get: () => (c.__dirty ? c.toDataURL("image/png") : null), clear: () => { c.getContext("2d").clearRect(0, 0, c.width, c.height); c.__dirty = false; } };
  }, []);
  const pos = (e) => { const c = canvasRef.current; const r = c.getBoundingClientRect(); const t = e.touches ? e.touches[0] : e; return { x: t.clientX - r.left, y: t.clientY - r.top }; };
  const start = (e) => { e.preventDefault(); drawing.current = true; const ctx = canvasRef.current.getContext("2d"); const p = pos(e); ctx.beginPath(); ctx.moveTo(p.x, p.y); };
  const move = (e) => { if (!drawing.current) return; e.preventDefault(); const ctx = canvasRef.current.getContext("2d"); const p = pos(e); ctx.lineTo(p.x, p.y); ctx.stroke(); canvasRef.current.__dirty = true; };
  const end = () => { drawing.current = false; };
  return (
    <canvas ref={canvasRef} onMouseDown={start} onMouseMove={move} onMouseUp={end} onMouseLeave={end} onTouchStart={start} onTouchMove={move} onTouchEnd={end}
      style={{ width: "100%", height: 150, border: "2px dashed var(--border-default)", borderRadius: "var(--radius-lg)", background: "var(--surface-sunken)", touchAction: "none", cursor: "crosshair", display: "block" }} />
  );
}

function SigningModal({ name, repName, onSave, onCancel, K }) {
  const [mode, setMode] = React.useState("type");       // 'type' | 'draw'
  const [typed, setTyped] = React.useState(name || "");
  const [repTyped, setRepTyped] = React.useState(repName || "");
  const [agree, setAgree] = React.useState(false);
  const [tick, setTick] = React.useState(0);            // forces re-eval of draw-ink presence
  const custInk = React.useRef(null);
  const today = new Date().toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" });

  const customerReady = mode === "type" ? typed.trim().length > 1 : true; // draw validated on adopt
  const adopt = () => {
    let customer;
    if (mode === "type") { if (typed.trim().length < 2) return; customer = { kind: "type", name: typed.trim() }; }
    else { const url = custInk.current && custInk.current.get(); if (!url) return; customer = { kind: "draw", dataUrl: url, name: typed.trim() || name }; }
    const rep = repTyped.trim() ? { kind: "type", name: repTyped.trim() } : null;
    onSave({ customer, rep });
  };

  const Tab = ({ id, icon, label }) => (
    <button onClick={() => setMode(id)} style={{ flex: 1, display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 7, padding: "9px 12px", borderRadius: "var(--radius-md)", border: "none", cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: "var(--text-xs)", fontWeight: 600, background: mode === id ? "#fff" : "transparent", color: mode === id ? "var(--color-primary-deep)" : "var(--text-muted)", boxShadow: mode === id ? "var(--shadow-xs)" : "none" }}>
      <Icon name={icon} size={15} />{label}
    </button>
  );

  return (
    <div style={{ position: "absolute", inset: 0, zIndex: 90, background: "rgba(28,26,24,0.5)", display: "flex", alignItems: "center", justifyContent: "center", padding: 24 }} onClick={onCancel}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: "min(560px, 100%)", maxHeight: "92vh", overflow: "auto", background: "#fff", borderRadius: "var(--radius-xl)", boxShadow: "var(--shadow-lg)" }}>
        <div style={{ padding: "18px 24px 14px", borderBottom: "1px solid var(--border-subtle)" }}>
          <K.Eyebrow tone="primary">Customer Signature</K.Eyebrow>
          <div style={{ fontSize: "var(--text-sm)", color: "var(--text-muted)", marginTop: 4 }}>Adopt your signature to execute the Residential Door Replacement Agreement.</div>
        </div>

        <div style={{ padding: "20px 24px 8px" }}>
          <div style={{ display: "flex", gap: 4, padding: 4, background: "var(--surface-sunken)", borderRadius: "var(--radius-lg)", marginBottom: 18 }}>
            <Tab id="type" icon="Type" label="Type" />
            <Tab id="draw" icon="PenLine" label="Draw" />
          </div>

          {mode === "type" ? (
            <div>
              <label style={{ display: "block", fontSize: "var(--text-2xs)", fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.1em", color: "var(--text-faint)", marginBottom: 7 }}>Full legal name</label>
              <input autoFocus value={typed} onChange={(e) => setTyped(e.target.value)} placeholder="Type your name"
                style={{ width: "100%", boxSizing: "border-box", height: 74, padding: "0 18px", borderRadius: "var(--radius-lg)", border: "2px solid var(--border-default)", background: "var(--surface-sunken)", outline: "none", fontFamily: "Georgia, 'Times New Roman', serif", fontStyle: "italic", fontSize: 32, color: "var(--text-primary)" }} />
              <div style={{ fontSize: 11, color: "var(--text-faint)", marginTop: 8 }}>This styled rendering of your name is your legally binding electronic signature.</div>
            </div>
          ) : (
            <div>
              <DrawPad inkRef={custInk} />
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 8 }}>
                <span style={{ fontSize: 11, color: "var(--text-faint)" }}>Draw with a finger, stylus, or mouse.</span>
                <button onClick={() => { custInk.current && custInk.current.clear(); setTick((t) => t + 1); }} style={{ border: "none", background: "transparent", cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: "var(--text-xs)", fontWeight: 600, color: "var(--text-muted)" }}>Clear</button>
              </div>
            </div>
          )}

          {/* Rep / witness */}
          <div style={{ marginTop: 18, paddingTop: 16, borderTop: "1px solid var(--border-subtle)" }}>
            <label style={{ display: "block", fontSize: "var(--text-2xs)", fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.1em", color: "var(--text-faint)", marginBottom: 7 }}>Company Rep / Witness <span style={{ fontWeight: 400, textTransform: "none", letterSpacing: 0 }}>(optional)</span></label>
            <input value={repTyped} onChange={(e) => setRepTyped(e.target.value)} placeholder="Rep or witness name"
              style={{ width: "100%", boxSizing: "border-box", height: 44, padding: "0 14px", borderRadius: "var(--radius-md)", border: "1px solid var(--border-default)", background: "var(--input-bg)", outline: "none", fontFamily: "var(--font-sans)", fontSize: "var(--text-sm)", color: "var(--text-primary)" }} />
          </div>

          {/* Consent */}
          <button onClick={() => setAgree((a) => !a)} style={{ display: "flex", alignItems: "flex-start", gap: 10, marginTop: 16, padding: 0, border: "none", background: "transparent", cursor: "pointer", textAlign: "left", width: "100%" }}>
            <span style={{ width: 18, height: 18, flexShrink: 0, marginTop: 1, borderRadius: 5, border: `1.5px solid ${agree ? "var(--color-primary-deep)" : "var(--border-strong)"}`, background: agree ? "var(--color-primary-deep)" : "#fff", display: "flex", alignItems: "center", justifyContent: "center" }}>{agree && <Icon name="Check" size={12} color="#fff" />}</span>
            <span style={{ fontSize: 11.5, lineHeight: 1.5, color: "var(--text-muted)" }}>I, {name}, agree this electronic signature, dated {today}, is legally binding and that I have reviewed the Agreement and Exhibits A–D.</span>
          </button>
        </div>

        <div style={{ display: "flex", justifyContent: "flex-end", gap: 10, padding: "8px 24px 22px" }}>
          <K.Button variant="outline" size="md" onClick={onCancel}>Cancel</K.Button>
          <K.Button variant="deep" size="md" disabled={!agree || !customerReady} onClick={adopt}><Icon name="Check" size={15} />Adopt &amp; Sign</K.Button>
        </div>
      </div>
    </div>
  );
}

// ── Dark-forest "Saved to records" confirmation hero ─────────────────────────
function SavedToRecords({ cust, total, signer, onClose, onViewRecords, K }) {
  const when = new Date().toLocaleString("en-US", { month: "long", day: "numeric", year: "numeric", hour: "numeric", minute: "2-digit" });
  return (
    <div style={{ position: "absolute", inset: 0, zIndex: 95, background: "rgba(20,28,25,0.62)", display: "flex", alignItems: "center", justifyContent: "center", padding: 24 }} onClick={onClose}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: "min(480px, 100%)", background: "linear-gradient(160deg, #19332F 0%, #1A2E27 100%)", borderRadius: "var(--radius-2xl)", boxShadow: "var(--shadow-lg)", padding: "40px 36px 32px", textAlign: "center", color: "#fff" }}>
        <div style={{ width: 72, height: 72, margin: "0 auto 22px", borderRadius: "50%", background: "rgba(255,255,255,0.1)", display: "flex", alignItems: "center", justifyContent: "center", boxShadow: "0 0 0 6px rgba(255,255,255,0.05)" }}>
          <Icon name="ShieldCheck" size={36} color="#fff" />
        </div>
        <div style={{ fontSize: "var(--text-2xs)", fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.14em", color: "rgba(255,255,255,0.55)", marginBottom: 10 }}>Saved to Records</div>
        <h2 style={{ margin: "0 0 8px", fontSize: "var(--text-2xl)", fontWeight: 700, letterSpacing: "-0.01em", color: "#fff" }}>Contract executed</h2>
        <p style={{ margin: "0 0 24px", fontSize: "var(--text-sm)", lineHeight: 1.6, color: "rgba(255,255,255,0.7)" }}>Thank you, {signer || cust.name}. Your agreement is now a locked record. A copy is on its way to {cust.email}.</p>

        <div style={{ background: "rgba(255,255,255,0.06)", borderRadius: "var(--radius-lg)", padding: "16px 18px", textAlign: "left", display: "flex", flexDirection: "column", gap: 10, marginBottom: 26 }}>
          {[["Agreement", "Door Replacement"], ["Signed by", signer || cust.name], ["Total investment", fmtD(total)], ["Recorded", when]].map(([k, v]) => (
            <div key={k} style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 16 }}>
              <span style={{ fontSize: "var(--text-2xs)", textTransform: "uppercase", letterSpacing: "0.08em", color: "rgba(255,255,255,0.5)", fontWeight: 600 }}>{k}</span>
              <span style={{ fontSize: "var(--text-sm)", fontWeight: 600, color: "#fff", fontVariantNumeric: "tabular-nums", textAlign: "right" }}>{v}</span>
            </div>
          ))}
        </div>

        <div style={{ display: "flex", gap: 10 }}>
          <button onClick={onClose} style={{ flex: 1, padding: "12px", borderRadius: "var(--radius-lg)", border: "1px solid rgba(255,255,255,0.2)", background: "transparent", color: "#fff", cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: "var(--text-sm)", fontWeight: 600 }}>View Document</button>
          <button onClick={onViewRecords} style={{ flex: 1, padding: "12px", borderRadius: "var(--radius-lg)", border: "none", background: "#fff", color: "var(--color-primary-deep)", cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: "var(--text-sm)", fontWeight: 700, display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 6 }}><Icon name="FileSignature" size={15} />Go to Contracts</button>
        </div>
        <div style={{ fontSize: 10.5, color: "rgba(255,255,255,0.4)", marginTop: 16 }}>Electronically signed &amp; stored per the E-SIGN Act. Bexar County, TX.</div>
      </div>
    </div>
  );
}

window.Contract = Contract;
