// csr-quotes.jsx — CE quotes repository: customer- vs agent-made, convert to booking, + dashboard.
const { useState: useStateQt, useMemo: useMemoQt } = React;

function qRangeBounds(r, from, to) {
  const now = new Date();
  if (r === "this") return [new Date(now.getFullYear(), now.getMonth(), 1), new Date(now.getFullYear(), now.getMonth() + 1, 1)];
  if (r === "last") return [new Date(now.getFullYear(), now.getMonth() - 1, 1), new Date(now.getFullYear(), now.getMonth(), 1)];
  if (r === "30") { const s = new Date(now); s.setDate(s.getDate() - 30); return [s, new Date(now.getTime() + 864e5)]; }
  if (r === "custom") return [from ? new Date(from) : new Date(0), to ? new Date(new Date(to).getTime() + 864e5) : new Date(now.getTime() + 864e5)];
  return [new Date(0), new Date(now.getTime() + 864e5)];
}

function QuoteSourcePill({ q }) {
  if (q.source === "agent") return <Badge tone="brand"><Icon name="headset" size={11} /> {q.agentName || "Agent"}</Badge>;
  return <Badge tone="neutral"><Icon name="user" size={11} /> Customer</Badge>;
}
function QuoteStatusPill({ q }) {
  if (q.status === "booked") return <Badge tone="success"><StatusDot color="#22b86e" /> Converted</Badge>;
  const expired = window.FX.quoteDaysLeft(q.expiresAt) <= 0;
  if (expired) return <Badge tone="neutral"><StatusDot color="var(--fg-faint)" /> Expired</Badge>;
  return <Badge tone="warn"><StatusDot color="var(--warn)" /> Open</Badge>;
}

function CsrQuotes({ quotes, customers, currency, currentUser, onConvert, onSaveQuote, onCreateQuote, onNotify }) {
  const money = (n) => window.FX.money(n, currency);
  const [range, setRange] = useStateQt("30");
  const [rFrom, setRFrom] = useStateQt("");
  const [rTo, setRTo] = useStateQt("");
  const [srcFilter, setSrcFilter] = useStateQt("all");
  const [statusFilter, setStatusFilter] = useStateQt("all");
  const [q, setQ] = useStateQt("");
  const [tab, setTab] = useStateQt("list");
  const [formOpen, setFormOpen] = useStateQt(false);
  const [formSeed, setFormSeed] = useStateQt(null);
  const openForm = (qt) => { setFormSeed(qt); setFormOpen(true); };

  const [rStart, rEnd] = qRangeBounds(range, rFrom, rTo);
  const inRange = useMemoQt(() => quotes.filter(qt => { const d = new Date(qt.createdAt); return d >= rStart && d < rEnd; }), [quotes, range, rFrom, rTo]);

  const m = useMemoQt(() => {
    const booked = inRange.filter(x => x.status === "booked");
    const byCustomer = inRange.filter(x => x.source !== "agent");
    const byAgent = inRange.filter(x => x.source === "agent");
    const valueQuoted = inRange.reduce((s, x) => s + (x.total || 0), 0);
    const valueConverted = booked.reduce((s, x) => s + (x.total || 0), 0);
    return { total: inRange.length, booked: booked.length, byCustomer: byCustomer.length, byAgent: byAgent.length, valueQuoted, valueConverted, convRate: inRange.length ? booked.length / inRange.length : 0 };
  }, [inRange]);

  const leaderboard = useMemoQt(() => {
    const map = {};
    inRange.forEach(x => {
      const key = x.source === "agent" ? (x.agentName || "Agent") : "Customer (self-service)";
      const row = map[key] || (map[key] = { who: key, isAgent: x.source === "agent", quotes: 0, converted: 0, valueQuoted: 0, valueConverted: 0 });
      row.quotes++; row.valueQuoted += x.total || 0;
      if (x.status === "booked") { row.converted++; row.valueConverted += x.total || 0; }
    });
    return Object.values(map).map(r => ({ ...r, rate: r.quotes ? r.converted / r.quotes : 0 })).sort((a, b) => b.converted - a.converted || b.quotes - a.quotes);
  }, [inRange]);

  const list = useMemoQt(() => {
    let l = inRange;
    if (srcFilter !== "all") l = l.filter(x => srcFilter === "agent" ? x.source === "agent" : x.source !== "agent");
    if (statusFilter === "booked") l = l.filter(x => x.status === "booked");
    if (statusFilter === "active") l = l.filter(x => x.status !== "booked");
    if (q.trim()) { const t = q.trim().toLowerCase(); l = l.filter(x => (x.no + " " + x.customerName + " " + (x.agentName || "") + " " + x.from + " " + x.to).toLowerCase().includes(t)); }
    return [...l].sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
  }, [inRange, srcFilter, statusFilter, q]);

  const rangeLabel = { this: "This month", last: "Last month", "30": "Last 30 days", all: "All time", custom: "Custom range" }[range];
  const pct = (n) => Math.round(n * 100) + "%";
  const maxLbConv = Math.max(1, ...leaderboard.map(r => r.converted));

  const stat = (label, value, sub, color) => (
    <Card pad={18}>
      <div style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.8px", textTransform: "uppercase", color: "var(--fg-mute)" }}>{label}</div>
      <div style={{ fontSize: 27, fontWeight: 900, color: color || "var(--fg-strong)", marginTop: 6, letterSpacing: "-0.5px" }}>{value}</div>
      {sub && <div style={{ fontSize: 12, color: "var(--fg-mute)", marginTop: 2 }}>{sub}</div>}
    </Card>
  );

  return (
    <div className="fade-up">
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", gap: 16, marginBottom: 18, flexWrap: "wrap" }}>
        <div>
          <Eyebrow>Customer service</Eyebrow>
          <h1 style={{ margin: "9px 0 0", fontSize: 25, fontWeight: 700, letterSpacing: "-0.6px", color: "var(--fg-strong)" }}>Quotes</h1>
          <p style={{ margin: "7px 0 0", fontSize: 14.5, color: "var(--fg-mute)" }}>Every quote — raised by a customer online or by an agent on a call — with conversion tracking.</p>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 8, alignItems: "flex-end" }}>
          <Button variant="primary" size="sm" icon="plus" onClick={() => openForm(null)}>New quote</Button>
          <div style={{ display: "inline-flex", gap: 6, background: "var(--bg-mist)", padding: 4, borderRadius: "var(--r-pill)" }}>
            {[["list", "Quotes"], ["dashboard", "Dashboard"]].map(([k, l]) => (
              <button key={k} onClick={() => setTab(k)} style={{ padding: "7px 16px", borderRadius: "var(--r-pill)", border: "none", fontSize: 13, fontWeight: 600, background: tab === k ? "var(--surface)" : "transparent", color: tab === k ? "var(--brand)" : "var(--fg-mute)", boxShadow: tab === k ? "var(--shadow-xs)" : "none", cursor: "pointer" }}>{l}</button>
            ))}
          </div>
          <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
            {[["this", "This month"], ["last", "Last month"], ["30", "30 days"], ["all", "All time"], ["custom", "Custom"]].map(([k, l]) => (
              <button key={k} onClick={() => setRange(k)} style={{ padding: "6px 12px", borderRadius: "var(--r-pill)", fontSize: 12, fontWeight: 500, border: "1px solid " + (range === k ? "var(--brand)" : "var(--border)"), background: range === k ? "var(--brand-soft)" : "var(--surface)", color: range === k ? "var(--brand)" : "var(--fg-mute)" }}>{l}</button>
            ))}
          </div>
        </div>
      </div>

      {range === "custom" && (
        <div style={{ display: "flex", gap: 12, marginBottom: 16, alignItems: "end", flexWrap: "wrap" }}>
          <Field label="From"><TextInput type="date" value={rFrom} onChange={setRFrom} /></Field>
          <Field label="To"><TextInput type="date" value={rTo} onChange={setRTo} /></Field>
        </div>
      )}

      {/* dashboard */}
      {tab === "dashboard" && (<React.Fragment>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, marginBottom: 14 }}>
        {stat("Quotes", m.total, rangeLabel)}
        {stat("Converted", m.booked, pct(m.convRate) + " conversion")}
        {stat("Value quoted", money(m.valueQuoted), null)}
        {stat("Value converted", money(m.valueConverted), m.valueQuoted ? pct(m.valueConverted / m.valueQuoted) + " of quoted" : null, "var(--success, #1f8a5b)")}
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "300px minmax(0,1fr)", gap: 14, marginBottom: 22 }}>
        {/* source split */}
        <Card pad={18}>
          <div style={{ fontSize: 13.5, fontWeight: 700, color: "var(--fg-strong)", marginBottom: 12 }}>By source</div>
          {[["Customer", m.byCustomer, "var(--fg-mute)"], ["Agent", m.byAgent, "var(--brand)"]].map(([lbl, n, col]) => (
            <div key={lbl} style={{ marginBottom: 12 }}>
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5, marginBottom: 5 }}>
                <span style={{ color: "var(--fg-body)", fontWeight: 500 }}>{lbl}</span>
                <span style={{ fontFamily: "var(--font-mono)", fontWeight: 700, color: "var(--fg-strong)" }}>{n} · {m.total ? pct(n / m.total) : "0%"}</span>
              </div>
              <div style={{ height: 8, background: "var(--bg-mist)", borderRadius: 999, overflow: "hidden" }}><div style={{ width: (m.total ? n / m.total * 100 : 0) + "%", height: "100%", background: col, borderRadius: 999 }} /></div>
            </div>
          ))}
          <div style={{ fontSize: 11.5, color: "var(--fg-mute)", marginTop: 4 }}>Agent-raised quotes convert when a CE agent books them on the caller's behalf.</div>
        </Card>

        {/* leaderboard */}
        <Card pad={0} style={{ overflow: "hidden" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "14px 18px 10px" }}>
            <Icon name="history" size={15} color="var(--brand)" />
            <span style={{ fontSize: 13.5, fontWeight: 700, color: "var(--fg-strong)" }}>Leaderboard — quotes vs conversions</span>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr 1.2fr 1fr", gap: 10, padding: "8px 18px", background: "var(--bg-mist)", borderTop: "1px solid var(--border)", borderBottom: "1px solid var(--border)", fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.6px", textTransform: "uppercase", color: "var(--fg-mute)" }}>
            <span>Who</span><span>Quotes</span><span>Converted</span><span style={{ textAlign: "right" }}>Value conv.</span>
          </div>
          <div style={{ maxHeight: 520, overflowY: "auto" }}>
          {leaderboard.map((r, i) => (
            <div key={r.who} style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr 1.2fr 1fr", gap: 10, padding: "11px 18px", borderTop: i ? "1px solid var(--border)" : "none", alignItems: "center" }}>
              <span style={{ display: "flex", alignItems: "center", gap: 8, minWidth: 0 }}>
                <span style={{ width: 22, height: 22, borderRadius: "50%", flex: "none", background: r.isAgent ? "var(--brand)" : "var(--bg-mist-2)", color: r.isAgent ? "#fff" : "var(--fg-mute)", display: "inline-flex", alignItems: "center", justifyContent: "center", fontWeight: 700, fontSize: 9 }}>{r.isAgent ? r.who.split(/\s+/).map(w => w[0]).slice(0, 2).join("").toUpperCase() : <Icon name="user" size={11} />}</span>
                <span style={{ fontSize: 13, fontWeight: 600, color: "var(--fg-strong)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{r.who}</span>
              </span>
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 13, color: "var(--fg-body)" }}>{r.quotes}</span>
              <span style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <span style={{ flex: 1, height: 7, background: "var(--bg-mist)", borderRadius: 999, overflow: "hidden", minWidth: 30 }}><span style={{ width: (r.converted / maxLbConv * 100) + "%", height: "100%", background: "var(--accent)", borderRadius: 999, display: "block" }} /></span>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 12.5, fontWeight: 700, color: "var(--fg-strong)", minWidth: 44 }}>{r.converted} · {pct(r.rate)}</span>
              </span>
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 12.5, fontWeight: 600, color: "var(--fg-strong)", textAlign: "right" }}>{money(r.valueConverted)}</span>
            </div>
          ))}
          {leaderboard.length === 0 && <div style={{ padding: 28, textAlign: "center", fontSize: 13, color: "var(--fg-mute)" }}>No quotes in {rangeLabel.toLowerCase()}.</div>}
          </div>
        </Card>
      </div>
      </React.Fragment>)}

      {/* filters + list */}
      {tab === "list" && (<React.Fragment>
      <div style={{ display: "flex", gap: 10, marginBottom: 12, flexWrap: "wrap", alignItems: "center" }}>
        <div style={{ display: "flex", gap: 6 }}>
          {[["all", "All sources"], ["customer", "Customer"], ["agent", "Agent"]].map(([k, l]) => (
            <button key={k} onClick={() => setSrcFilter(k)} style={{ padding: "7px 13px", borderRadius: "var(--r-pill)", fontSize: 12.5, fontWeight: 500, border: "1px solid " + (srcFilter === k ? "var(--brand)" : "var(--border)"), background: srcFilter === k ? "var(--brand-soft)" : "var(--surface)", color: srcFilter === k ? "var(--brand)" : "var(--fg-mute)" }}>{l}</button>
          ))}
        </div>
        <div style={{ display: "flex", gap: 6 }}>
          {[["all", "Any status"], ["active", "Open"], ["booked", "Converted"]].map(([k, l]) => (
            <button key={k} onClick={() => setStatusFilter(k)} style={{ padding: "7px 13px", borderRadius: "var(--r-pill)", fontSize: 12.5, fontWeight: 500, border: "1px solid " + (statusFilter === k ? "var(--accent)" : "var(--border)"), background: statusFilter === k ? "var(--accent-soft)" : "var(--surface)", color: statusFilter === k ? "var(--accent-700)" : "var(--fg-mute)" }}>{l}</button>
          ))}
        </div>
        <div style={{ position: "relative", flex: "1 1 220px", minWidth: 180 }}>
          <span style={{ position: "absolute", left: 11, top: "50%", transform: "translateY(-50%)", color: "var(--fg-mute)" }}><Icon name="search" size={14} /></span>
          <input value={q} onChange={e => setQ(e.target.value)} placeholder="Search quote, customer or route…" style={{ ...window.inputStyle, paddingLeft: 34, paddingTop: 8, paddingBottom: 8, fontSize: 13 }} />
        </div>
      </div>

      <Card pad={0} style={{ overflow: "hidden" }}>
        <div style={{ display: "grid", gridTemplateColumns: "0.9fr 1.3fr 1.4fr 0.8fr 1fr 1fr 0.9fr", gap: 10, padding: "11px 18px", background: "var(--bg-mist)", borderBottom: "1px solid var(--border)", fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.6px", textTransform: "uppercase", color: "var(--fg-mute)" }}>
          <span>Quote</span><span>Customer</span><span>Route</span><span>Total</span><span>Source</span><span>Status</span><span style={{ textAlign: "right" }}>Action</span>
        </div>
        {list.map((qt, i) => (
          <div key={qt.no} onClick={() => openForm(qt)} style={{ display: "grid", gridTemplateColumns: "0.9fr 1.3fr 1.4fr 0.8fr 1fr 1fr 0.9fr", gap: 10, padding: "12px 18px", borderTop: i ? "1px solid var(--border)" : "none", alignItems: "center", cursor: "pointer" }} onMouseEnter={e => e.currentTarget.style.background = "var(--bg-mist)"} onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
            <span style={{ minWidth: 0 }}>
              <span style={{ display: "block", fontFamily: "var(--font-mono)", fontSize: 12.5, fontWeight: 700, color: "var(--brand)" }}>{qt.no}</span>
              <span style={{ display: "block", fontSize: 11, color: "var(--fg-mute)" }}>{window.FX.fmtDate((qt.createdAt || "").slice(0, 10))}</span>
            </span>
            <span style={{ fontSize: 13, color: "var(--fg-strong)", fontWeight: 500, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{qt.customerName}</span>
            <span style={{ fontSize: 12.5, color: "var(--fg-body)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{qt.from} → {qt.to}</span>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 13, fontWeight: 600, color: "var(--fg-strong)" }}>{money(qt.total)}</span>
            <span><QuoteSourcePill q={qt} /></span>
            <span>
              <QuoteStatusPill q={qt} />
              {qt.status === "booked" && qt.convertedBookingTracking && <span style={{ display: "block", fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--fg-mute)", marginTop: 3 }}>{qt.convertedBookingTracking}</span>}
            </span>
            <span style={{ textAlign: "right" }}>
              {qt.status === "booked"
                ? <span style={{ fontSize: 11.5, color: "var(--fg-mute)" }}>by {(qt.convertedBy || "—").split(/\s+/)[0]}</span>
                : <Button variant="primary" size="sm" icon="arrow-right" onClick={e => { e.stopPropagation(); onConvert(qt); }}>Convert</Button>}
            </span>
          </div>
        ))}
        {list.length === 0 && <div style={{ padding: 36, textAlign: "center", fontSize: 13.5, color: "var(--fg-mute)" }}>No quotes match these filters.</div>}
      </Card>
      </React.Fragment>)}

      <QuoteFormModal open={formOpen} onClose={() => setFormOpen(false)} seed={formSeed} customers={customers} currency={currency} currentUser={currentUser} onCreate={q => { onCreateQuote(q); setFormOpen(false); }} onSave={q => { onSaveQuote(q); setFormOpen(false); }} onConvert={qt => { setFormOpen(false); onConvert(qt); }} />
    </div>
  );
}

function QuoteFormModal({ open, onClose, seed, customers, currency, currentUser, onCreate, onSave, onConvert }) {
  const editing = !!seed;
  const [customerId, setCustomerId] = useStateQt("");
  const [from, setFrom] = useStateQt(""); const [fromPc, setFromPc] = useStateQt("");
  const [to, setTo] = useStateQt(""); const [toPc, setToPc] = useStateQt("");
  const [serviceId, setServiceId] = useStateQt("standard");
  const [vehicleId, setVehicleId] = useStateQt("courier");
  const [isReturn, setIsReturn] = useStateQt(false);
  React.useEffect(() => {
    if (open) {
      setCustomerId(seed ? seed.customerId : (customers[0] ? customers[0].id : ""));
      setFrom(seed ? seed.from : ""); setFromPc(seed ? (seed.fromPc || "") : "");
      setTo(seed ? seed.to : ""); setToPc(seed ? (seed.toPc || "") : "");
      setServiceId(seed ? seed.serviceId : "standard");
      setVehicleId(seed ? (seed.vehicleId || "courier") : "courier");
      setIsReturn(seed ? !!seed.isReturn : false);
    }
  }, [open, seed]);
  const cust = customers.find(c => c.id === customerId) || null;
  const bothKnown = from && to && window.FX.suburbState(from) && window.FX.suburbState(to);
  const isInterstate = !!(bothKnown && window.FX.suburbState(from) !== window.FX.suburbState(to));
  const km = (from && to) ? window.FX.distanceKm(from, to) : null;
  const total = (km != null) ? window.FX.quote({ vehicleId, km, serviceId, isReturn, rateMult: 1 }).total : 0;
  const booked = editing && seed.status === "booked";
  const ok = cust && from && to;
  function build() {
    const createdAt = editing ? seed.createdAt : new Date().toISOString();
    const base = { no: editing ? seed.no : window.FX.genQuoteNo(), customerId, customerName: cust.name, customerRef: cust.ref || "", source: editing ? seed.source : "agent", agentId: editing ? seed.agentId : currentUser.id, agentName: editing ? seed.agentName : (currentUser.name || "CE console"), from, fromPc, to, toPc, serviceId, vehicleId, isReturn, isInterstate, items: editing ? (seed.items || []) : [], total, km: km || 0, createdAt, expiresAt: window.FX.quoteExpiryISO(createdAt), status: editing ? seed.status : "active" };
    if (editing) { base.convertedBookingTracking = seed.convertedBookingTracking; base.convertedAt = seed.convertedAt; base.convertedBy = seed.convertedBy; }
    return base;
  }
  return (
    <Modal open={open} onClose={onClose} title={editing ? "Quote " + seed.no : "New quote"} width={560} top>
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        {editing && (
          <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap", padding: "10px 12px", background: "var(--bg-mist)", borderRadius: "var(--r-sm)" }}>
            <QuoteSourcePill q={seed} />
            <QuoteStatusPill q={seed} />
            <span style={{ fontSize: 12, color: "var(--fg-mute)" }}>Created {window.FX.fmtDate((seed.createdAt || "").slice(0, 10))}</span>
            {booked && seed.convertedBookingTracking && <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--fg-mute)" }}>· {seed.convertedBookingTracking}</span>}
          </div>
        )}
        <Field label="Customer"><Select value={customerId} onChange={setCustomerId} options={customers.map(c => ({ value: c.id, label: c.name + (c.ref ? " · " + c.ref : "") }))} placeholder="Select customer…" /></Field>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <Field label="From"><SuburbPostcodeField suburb={from} postcode={fromPc} onPick={(s, p) => { setFrom(s); setFromPc(p); }} /></Field>
          <Field label="To"><SuburbPostcodeField suburb={to} postcode={toPc} onPick={(s, p) => { setTo(s); setToPc(p); }} /></Field>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <Field label="Service tier"><Select value={serviceId} onChange={setServiceId} options={window.FX.SERVICES.map(s => ({ value: s.id, label: s.name + " · " + s.eta }))} /></Field>
          <Field label="Size"><Select value={vehicleId} onChange={setVehicleId} options={window.FX.VEHICLES.map(v => ({ value: v.id, label: v.name }))} /></Field>
        </div>
        <button onClick={() => setIsReturn(v => !v)} style={{ display: "flex", alignItems: "center", gap: 10, background: "transparent", border: "none", padding: 0, textAlign: "left", cursor: "pointer" }}>
          <span style={{ width: 38, height: 22, borderRadius: 999, flex: "none", background: isReturn ? "var(--accent)" : "var(--bg-mist-2)", position: "relative", transition: "all 160ms ease" }}><span style={{ position: "absolute", top: 2, left: isReturn ? 18 : 2, width: 18, height: 18, borderRadius: "50%", background: "#fff" }} /></span>
          <span style={{ fontSize: 13.5, color: "var(--fg-strong)", fontWeight: 500 }}>Return trip (−15% on the return leg)</span>
        </button>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "13px 15px", background: "var(--brand-soft)", borderRadius: "var(--r-md)" }}>
          <span style={{ fontSize: 13, color: "var(--fg-body)" }}>{isInterstate ? "Interstate · Next Flight" : "Indicative price"}{km != null ? " · " + km + " km" : ""}</span>
          <span style={{ fontSize: 22, fontWeight: 900, color: "var(--fg-strong)", letterSpacing: "-0.5px" }}>{window.FX.money(total, currency)}</span>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 2 }}>
          {editing && !booked
            ? <Button variant="secondary" icon="arrow-right" onClick={() => onConvert(seed)}>Convert to booking →</Button>
            : <span />}
          <div style={{ display: "flex", gap: 10, marginLeft: "auto" }}>
            <Button variant="ghost" onClick={onClose}>Cancel</Button>
            {!booked && <Button variant="primary" icon="check" disabled={!ok} onClick={() => editing ? onSave(build()) : onCreate(build())}>{editing ? "Save quote" : "Create quote"}</Button>}
          </div>
        </div>
      </div>
    </Modal>
  );
}

Object.assign(window, { CsrQuotes, QuoteSourcePill, QuoteStatusPill, QuoteFormModal });
