/* Contracts — saved contract records over window.CONTRACTS (read + open).
   Searchable list filtered by status (Draft / Sent / Signed / Void); each row
   opens the executed document. Miney wires the Supabase reads + save. */

const { Card: CtCard, Eyebrow: CtEyebrow } = window.Ds1Threshold_e046d3;

const CT_STATUS = {
  signed: { label: "Signed", dot: "var(--status-sold-solid)",    bg: "var(--status-sold-bg)",    fg: "var(--status-sold-fg)",    icon: "ShieldCheck" },
  sent:   { label: "Sent",   dot: "var(--status-info-solid)",    bg: "var(--status-info-bg)",    fg: "var(--status-info-fg)",    icon: "Send" },
  draft:  { label: "Draft",  dot: "var(--status-pending-solid)", bg: "var(--status-pending-bg)", fg: "var(--status-pending-fg)", icon: "FileText" },
  void:   { label: "Void",   dot: "var(--text-faint)",           bg: "var(--surface-sunken)",    fg: "var(--text-muted)",        icon: "Ban" },
};

function CtStatusPill({ status }) {
  const s = CT_STATUS[status] || CT_STATUS.draft;
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "4px 11px", borderRadius: "var(--radius-full)", background: s.bg, color: s.fg, fontSize: "var(--text-2xs)", fontWeight: 700, whiteSpace: "nowrap" }}>
      <Icon name={s.icon} size={12} />{s.label}
    </span>
  );
}

function Contracts({ onOpen }) {
  const CT = window.CONTRACTS;
  const counts = CT.counts();
  const [q, setQ] = React.useState("");
  const [filter, setFilter] = React.useState("all");
  const sync = Math.max(1, Math.round((Date.now() - CT.lastSyncMs) / 60000));

  const t = q.trim().toLowerCase();
  const rows = CT.sortedRecent().filter((r) => {
    const hitQ = !t || [r.customer, r.id, r.quote_id, r.signer_name || "", (r.data && r.data.address) || ""].some((v) => String(v).toLowerCase().includes(t));
    return hitQ && (filter === "all" || r.status === filter);
  });

  const tabs = [["all", "All", CT.total], ["signed", "Signed", counts.signed], ["sent", "Sent", counts.sent], ["draft", "Draft", counts.draft], ["void", "Void", counts.void]];

  return (
    <div style={{ maxWidth: "var(--content-max)", margin: "0 auto" }}>
      <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 16, marginBottom: 22 }}>
        <div>
          <h1 style={{ margin: 0, fontSize: "var(--text-2xl)", fontWeight: 700, letterSpacing: "-0.02em", color: "var(--text-primary)" }}>Contracts</h1>
          <p style={{ margin: "4px 0 0", fontSize: "var(--text-sm)", color: "var(--text-muted)" }}>Signed agreements &amp; documents on record · {CT.total} total</p>
        </div>
        <div style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "6px 12px", borderRadius: "var(--radius-full)", background: "var(--surface-sunken)", border: "1px solid var(--border-subtle)" }}>
          <Icon name="RefreshCw" size={12} color="var(--text-muted)" />
          <span style={{ fontSize: "var(--text-2xs)", fontWeight: 600, color: "var(--text-muted)", textTransform: "uppercase", letterSpacing: "0.08em" }}>Synced {sync}m ago</span>
        </div>
      </div>

      {/* Status filter tabs + search */}
      <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 16, flexWrap: "wrap" }}>
        <div style={{ display: "flex", background: "var(--surface-sunken)", border: "1px solid var(--border-subtle)", borderRadius: "var(--radius-lg)", padding: 3, gap: 2 }}>
          {tabs.map(([key, label, n]) => (
            <button key={key} onClick={() => setFilter(key)} style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "7px 14px", borderRadius: "var(--radius-md)", border: "none", cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: "var(--text-xs)", fontWeight: 600, background: filter === key ? "var(--surface-card)" : "transparent", color: filter === key ? "var(--text-primary)" : "var(--text-muted)", boxShadow: filter === key ? "var(--shadow-xs)" : "none" }}>
              {label}<span style={{ fontVariantNumeric: "tabular-nums", fontWeight: 700, color: filter === key ? "var(--color-primary-deep)" : "var(--text-faint)" }}>{n}</span>
            </button>
          ))}
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 9, background: "var(--input-bg)", border: "1px solid var(--border-subtle)", borderRadius: "var(--radius-lg)", padding: "9px 13px", flex: "1 1 240px", minWidth: 200 }}>
          <Icon name="Search" size={16} color="var(--text-muted)" />
          <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search customer, contract or quote #…" style={{ border: "none", outline: "none", background: "transparent", fontFamily: "var(--font-sans)", fontSize: "var(--text-sm)", color: "var(--text-primary)", width: "100%" }} />
        </div>
      </div>

      {/* Records table */}
      <CtCard padding="none" style={{ overflow: "hidden" }}>
        <div style={{ display: "grid", gridTemplateColumns: "1.7fr 1fr 1.1fr 0.9fr 110px", gap: 16, padding: "11px 22px", background: "var(--surface-sunken)", borderBottom: "1px solid var(--border-subtle)" }}>
          {["Customer", "Status", "Signed", "Investment", ""].map((h, i) => (
            <CtEyebrow key={i} size="2xs" style={{ textAlign: i === 3 ? "right" : "left" }}>{h}</CtEyebrow>
          ))}
        </div>
        {rows.length === 0 && <div style={{ padding: 32, textAlign: "center", fontSize: "var(--text-sm)", color: "var(--text-muted)" }}>No contracts match your search.</div>}
        {rows.map((r) => {
          const openable = r.status === "signed" || r.status === "sent" || r.status === "draft";
          return (
            <div key={r.id} onClick={() => openable && onOpen && onOpen(r)} style={{ display: "grid", gridTemplateColumns: "1.7fr 1fr 1.1fr 0.9fr 110px", gap: 16, padding: "14px 22px", alignItems: "center", borderBottom: "1px solid var(--border-subtle)", cursor: openable ? "pointer" : "default", opacity: r.status === "void" ? 0.6 : 1 }}
              onMouseEnter={(e) => { if (openable) e.currentTarget.style.background = "var(--surface-sunken)"; }}
              onMouseLeave={(e) => { e.currentTarget.style.background = "transparent"; }}>
              <div style={{ display: "flex", alignItems: "center", gap: 12, minWidth: 0 }}>
                <span style={{ width: 38, height: 38, flexShrink: 0, borderRadius: "var(--radius-md)", background: r.status === "signed" ? "var(--color-primary-soft)" : "var(--surface-sunken)", border: "1px solid var(--border-subtle)", display: "flex", alignItems: "center", justifyContent: "center", color: r.status === "signed" ? "var(--color-primary-deep)" : "var(--text-muted)" }}>
                  <Icon name={r.status === "signed" ? "FileCheck2" : "FileSignature"} size={18} />
                </span>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: "var(--text-sm)", fontWeight: 700, color: "var(--text-primary)" }}>{r.customer}</div>
                  <div style={{ fontSize: "var(--text-xs)", color: "var(--text-muted)", marginTop: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{r.id} · Quote {r.quote_id}</div>
                </div>
              </div>
              <div><CtStatusPill status={r.status} /></div>
              <div>
                {r.signed_at
                  ? <div><div style={{ fontSize: "var(--text-sm)", color: "var(--text-secondary)", fontVariantNumeric: "tabular-nums" }}>{CT.fmtSignedDate(r.signed_at)}</div><div style={{ fontSize: "var(--text-2xs)", color: "var(--text-faint)", marginTop: 1 }}>{r.signer_name} · {CT.relDate(r.signed_at)}</div></div>
                  : <span style={{ fontSize: "var(--text-xs)", color: "var(--text-faint)" }}>—</span>}
              </div>
              <div style={{ textAlign: "right", fontSize: "var(--text-sm)", fontWeight: 700, color: "var(--text-primary)", fontVariantNumeric: "tabular-nums" }}>{fmtD(r.total)}</div>
              <div style={{ textAlign: "right" }}>
                {openable
                  ? <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: "var(--text-xs)", fontWeight: 600, color: "var(--color-primary-deep)" }}>Open<Icon name="ArrowUpRight" size={14} /></span>
                  : <span style={{ fontSize: "var(--text-2xs)", color: "var(--text-faint)" }}>Voided</span>}
              </div>
            </div>
          );
        })}
      </CtCard>

      <div style={{ display: "flex", alignItems: "center", gap: 7, marginTop: 14, fontSize: "var(--text-2xs)", color: "var(--text-faint)" }}>
        <Icon name="Lock" size={12} />Signed contracts are locked records. Electronically signed &amp; stored per the E-SIGN Act.
      </div>
    </div>
  );
}

window.Contracts = Contracts;
