// account.jsx — Invoices, Payment methods, Team users
const { useState: useStateAcc } = React;

/* ============== INVOICES ============== */
function InvoiceDoc({ inv, account, currency }) {
  const sub = inv.amount / 1.1, gst = inv.amount - sub;
  const cell = { padding: "10px 0", fontSize: 13.5 };
  return (
    <div className="print-area" style={{ background: "#fff", border: "1px solid #d8d3e0", borderRadius: 12, overflow: "hidden", width: "100%", maxWidth: 600, fontFamily: "var(--font-sans)" }}>
      <div style={{ background: "var(--brand)", color: "#fff", padding: "22px 26px", display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
        <div>
          <Wordmark size={26} onDark />
          <div style={{ fontSize: 12.5, opacity: 0.8, marginTop: 8 }}>Tax Invoice</div>
        </div>
        <div style={{ textAlign: "right" }}>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 16, fontWeight: 600 }}>{inv.id}</div>
          <div style={{ fontSize: 12, opacity: 0.8, marginTop: 4 }}>Issued {window.FX.fmtDate(inv.date)}</div>
        </div>
      </div>
      <div style={{ padding: "22px 26px", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, borderBottom: "1px solid #eee" }}>
        <div>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "1px", textTransform: "uppercase", color: "#8a8499", marginBottom: 6 }}>Billed to</div>
          <div style={{ fontWeight: 700, fontSize: 14.5, color: "#16121f" }}>{account ? account.name : window.FX.COMPANY}</div>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 12.5, color: "#4a4e64", marginTop: 2 }}>{account ? account.number : ""}</div>
        </div>
        <div style={{ textAlign: "right" }}>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "1px", textTransform: "uppercase", color: "#8a8499", marginBottom: 6 }}>Due date</div>
          <div style={{ fontWeight: 700, fontSize: 14.5, color: inv.status === "Due" ? "var(--accent-700)" : "#16121f" }}>{window.FX.fmtDate(inv.due)}</div>
          <div style={{ marginTop: 6 }}><Badge tone={inv.status === "Paid" ? "success" : "warn"}>{inv.status}</Badge></div>
        </div>
      </div>
      <div style={{ padding: "12px 26px" }}>
        <div style={{ display: "flex", justifyContent: "space-between", borderBottom: "1px solid #eee", ...cell, color: "#8a8499", fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.6px", textTransform: "uppercase" }}>
          <span>Description</span><span>Amount</span>
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", borderBottom: "1px solid #f3f3f3", ...cell }}>
          <span style={{ color: "#16121f" }}>Same-day deliveries — {inv.period} ({inv.deliveries} jobs)</span>
          <span style={{ color: "#16121f", fontWeight: 500 }}>{window.FX.money(sub, currency)}</span>
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", ...cell }}>
          <span style={{ color: "#4a4e64" }}>GST (10%)</span><span style={{ color: "#4a4e64" }}>{window.FX.money(gst, currency)}</span>
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", padding: "14px 0 4px", borderTop: "2px solid #16121f", marginTop: 4 }}>
          <span style={{ fontWeight: 700, fontSize: 16, color: "#16121f" }}>Total {currency}</span>
          <span style={{ fontWeight: 900, fontSize: 22, color: "#16121f", letterSpacing: "-0.5px" }}>{window.FX.money(inv.amount, currency)}</span>
        </div>
      </div>
      <div style={{ background: "#16121f", color: "rgba(255,255,255,0.7)", padding: "12px 26px", fontSize: 11, fontFamily: "var(--font-mono)" }}>
        Fedex Australia Pty Ltd · ABN 12 345 678 901 · 12 Coward St, Mascot NSW 2020
      </div>
    </div>
  );
}

function Invoices({ currency, account }) {
  const [view, setView] = useStateAcc(null);
  const all = window.FX.INVOICES.filter(i => !account || i.accountId === account.id);
  const outstanding = all.filter(i => i.status === "Due").reduce((s, i) => s + i.amount, 0);

  function download(inv) {
    const win = window.open("", "_blank");
    const node = document.getElementById("invoice-print-root");
    if (!win || !node) { window.print(); return; }
    win.document.write(`<!doctype html><html><head><title>${inv.id}</title><style>body{margin:0;font-family:Roboto,Arial,sans-serif;background:#f3f1ee;padding:24px;display:flex;justify-content:center;}</style></head><body>${node.innerHTML}</body></html>`);
    win.document.close(); setTimeout(() => win.print(), 300);
  }

  return (
    <div className="fade-up">
      <PageHeader eyebrow="Billing" title="Invoices" sub="Download tax invoices and statements for your account." />
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 16, marginBottom: 22 }}>
        <Card pad={20}><div style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.8px", textTransform: "uppercase", color: "var(--fg-mute)" }}>Outstanding</div><div style={{ fontSize: 30, fontWeight: 900, letterSpacing: "-1px", color: outstanding > 0 ? "var(--accent-700)" : "var(--fg-strong)", marginTop: 8 }}>{window.FX.money(outstanding, currency)}</div><div style={{ fontSize: 12.5, color: "var(--fg-mute)", marginTop: 4 }}>{all.filter(i => i.status === "Due").length} invoice due</div></Card>
        <Card pad={20}><div style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.8px", textTransform: "uppercase", color: "var(--fg-mute)" }}>Account</div><div style={{ fontSize: 18, fontWeight: 700, color: "var(--fg-strong)", marginTop: 10 }}>{account ? account.name : "—"}</div><div style={{ fontFamily: "var(--font-mono)", fontSize: 12.5, color: "var(--fg-mute)", marginTop: 4 }}>{account ? account.number : ""}</div></Card>
        <Card pad={20}><div style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.8px", textTransform: "uppercase", color: "var(--fg-mute)" }}>Billing cycle</div><div style={{ fontSize: 18, fontWeight: 700, color: "var(--fg-strong)", marginTop: 10 }}>Monthly</div><div style={{ fontSize: 12.5, color: "var(--fg-mute)", marginTop: 4 }}>Net 30 · direct debit</div></Card>
      </div>

      <Card pad={0} style={{ overflow: "hidden" }}>
        <div style={{ display: "grid", gridTemplateColumns: "1.2fr 1fr 0.8fr 1fr 0.9fr 130px", gap: 12, padding: "13px 22px", background: "var(--bg-mist)", borderBottom: "1px solid var(--border)", fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.8px", textTransform: "uppercase", color: "var(--fg-mute)" }}>
          <span>Invoice</span><span>Period</span><span>Jobs</span><span>Amount</span><span>Status</span><span style={{ textAlign: "right" }}>Actions</span>
        </div>
        {all.map((inv, i) => (
          <div key={inv.id} style={{ display: "grid", gridTemplateColumns: "1.2fr 1fr 0.8fr 1fr 0.9fr 130px", gap: 12, padding: "15px 22px", borderTop: i ? "1px solid var(--border)" : "none", alignItems: "center" }}>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 13, fontWeight: 600, color: "var(--brand)" }}>{inv.id}</span>
            <span style={{ fontSize: 13.5, color: "var(--fg-body)" }}>{inv.period}</span>
            <span style={{ fontSize: 13.5, color: "var(--fg-mute)" }}>{inv.deliveries}</span>
            <span style={{ fontSize: 14, fontWeight: 700, color: "var(--fg-strong)" }}>{window.FX.money(inv.amount, currency)}</span>
            <span><Badge tone={inv.status === "Paid" ? "success" : "warn"}><StatusDot color={inv.status === "Paid" ? "#22b86e" : "var(--warn)"} /> {inv.status}</Badge></span>
            <span style={{ display: "flex", gap: 6, justifyContent: "flex-end" }}>
              <button onClick={() => setView(inv)} title="View" style={{ background: "var(--bg-mist)", border: "none", borderRadius: 8, width: 34, height: 34, display: "inline-flex", alignItems: "center", justifyContent: "center", color: "var(--fg-body)" }}><Icon name="external-link" size={16} /></button>
              <button onClick={() => setView(inv)} title="Download" style={{ background: "var(--brand-soft)", border: "none", borderRadius: 8, width: 34, height: 34, display: "inline-flex", alignItems: "center", justifyContent: "center", color: "var(--brand)" }}><Icon name="download" size={16} /></button>
            </span>
          </div>
        ))}
        {all.length === 0 && <div style={{ padding: 40, textAlign: "center", color: "var(--fg-mute)" }}>No invoices for this account yet.</div>}
      </Card>

      {view && (
        <Modal open={!!view} onClose={() => setView(null)} title={"Invoice " + view.id} width={640}>
          <div id="invoice-print-root" style={{ display: "flex", justifyContent: "center", marginBottom: 18 }}>
            <InvoiceDoc inv={view} account={account} currency={currency} />
          </div>
          <div className="no-print" style={{ display: "flex", gap: 10 }}>
            <Button variant="primary" full icon="download" onClick={() => download(view)}>Download PDF</Button>
            <Button variant="secondary" icon="printer" onClick={() => window.print()}>Print</Button>
          </div>
        </Modal>
      )}
    </div>
  );
}

/* ============== PAYMENT METHODS ============== */
function brandOf(num) {
  const n = num.replace(/\s/g, "");
  if (/^4/.test(n)) return "Visa";
  if (/^5[1-5]/.test(n) || /^2[2-7]/.test(n)) return "Mastercard";
  if (/^3[47]/.test(n)) return "Amex";
  return "Card";
}
function PaymentMethods({ methods, onAdd, onRemove, onSetPrimary }) {
  const [adding, setAdding] = useStateAcc(false);
  const [num, setNum] = useStateAcc(""); const [name, setName] = useStateAcc("");
  const [exp, setExp] = useStateAcc(""); const [cvc, setCvc] = useStateAcc("");
  const fmtNum = v => v.replace(/\D/g, "").slice(0, 16).replace(/(.{4})/g, "$1 ").trim();
  const valid = num.replace(/\s/g, "").length >= 15 && name && /^\d{2}\/\d{2}$/.test(exp) && cvc.length >= 3;
  function save() {
    if (!valid) return;
    onAdd({ id: "pm" + Date.now(), brand: brandOf(num), last4: num.replace(/\s/g, "").slice(-4), exp, name, primary: methods.length === 0 });
    setNum(""); setName(""); setExp(""); setCvc(""); setAdding(false);
  }
  return (
    <div className="fade-up">
      <PageHeader eyebrow="Billing" title="Payment methods" sub="Update how you pay — pay on account by direct debit, or add a credit card."
        actions={!adding && <Button variant="primary" icon="plus" onClick={() => setAdding(true)}>Add card</Button>} />
      <div style={{ display: "grid", gridTemplateColumns: "minmax(0,1fr) minmax(0,1fr)", gap: 24, alignItems: "start" }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          {methods.map(m => (
            <Card key={m.id} pad={20}>
              <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
                <span style={{ width: 52, height: 34, borderRadius: 7, background: "linear-gradient(135deg, var(--brand), var(--brand-700))", color: "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center", fontWeight: 700, fontSize: 12, flex: "none" }}>{m.brand}</span>
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 600, fontSize: 14.5, color: "var(--fg-strong)", fontFamily: "var(--font-mono)" }}>•••• •••• •••• {m.last4}</div>
                  <div style={{ fontSize: 12.5, color: "var(--fg-mute)", marginTop: 2 }}>{m.name} · exp {m.exp}</div>
                </div>
                {m.primary ? <Badge tone="brand">Primary</Badge> : <button onClick={() => onSetPrimary(m.id)} style={{ background: "transparent", border: "none", color: "var(--accent-700)", fontSize: 13, fontWeight: 500 }}>Make primary</button>}
                <button onClick={() => onRemove(m.id)} style={{ background: "var(--bg-mist)", border: "none", borderRadius: 8, width: 32, height: 32, display: "inline-flex", alignItems: "center", justifyContent: "center", color: "var(--fg-mute)" }}><Icon name="x" size={15} /></button>
              </div>
            </Card>
          ))}
          <Card pad={18} style={{ background: "var(--bg-mist)", borderStyle: "dashed" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
              <Icon name="wallet" size={18} color="var(--brand)" />
              <div style={{ flex: 1, fontSize: 13.5, color: "var(--fg-body)" }}><strong style={{ color: "var(--fg-strong)" }}>Pay on account</strong> — direct debit on the 30th. Active.</div>
              <Badge tone="success"><StatusDot color="#22b86e" /> On</Badge>
            </div>
          </Card>
        </div>

        {adding && (
          <Card pad={24} className="fade-up">
            <div style={{ fontWeight: 700, fontSize: 16, color: "var(--fg-strong)", marginBottom: 16 }}>Add a credit card</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
              <Field label="Card number"><TextInput value={num} onChange={v => setNum(fmtNum(v))} placeholder="4242 4242 4242 4242" mono /></Field>
              <Field label="Name on card"><TextInput value={name} onChange={setName} placeholder="Meridian Group Pty Ltd" /></Field>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
                <Field label="Expiry"><TextInput value={exp} onChange={v => setExp(v.replace(/[^\d]/g, "").slice(0,4).replace(/(\d{2})(\d)/, "$1/$2"))} placeholder="MM/YY" mono /></Field>
                <Field label="CVC"><TextInput value={cvc} onChange={v => setCvc(v.replace(/\D/g, "").slice(0,4))} placeholder="123" mono /></Field>
              </div>
              <div style={{ display: "flex", gap: 10, marginTop: 4 }}>
                <Button variant="ghost" onClick={() => setAdding(false)}>Cancel</Button>
                <Button variant="primary" full icon="check" onClick={save} disabled={!valid}>Save card</Button>
              </div>
              <div style={{ fontSize: 12, color: "var(--fg-mute)", display: "flex", alignItems: "center", gap: 6 }}><Icon name="shield-check" size={14} color="var(--success)" /> Encrypted · we never store the full number</div>
            </div>
          </Card>
        )}
      </div>
    </div>
  );
}

/* ============== USERS ============== */
const ROLES = ["Admin", "Booking", "View only"];
function Users({ users, onAdd, onRemove }) {
  const [open, setOpen] = useStateAcc(false);
  const [name, setName] = useStateAcc(""); const [email, setEmail] = useStateAcc(""); const [role, setRole] = useStateAcc("Booking");
  function add() {
    if (!name || !email) return;
    const initials = name.trim().split(/\s+/).map(p => p[0]).slice(0, 2).join("").toUpperCase();
    onAdd({ id: "u" + Date.now(), name, email, role, status: "Invited", initials });
    setName(""); setEmail(""); setRole("Booking"); setOpen(false);
  }
  const roleTone = r => r === "Admin" ? "brand" : r === "Booking" ? "accent" : "neutral";
  return (
    <div className="fade-up">
      <PageHeader eyebrow="Account" title="Users & team" sub="Invite colleagues and control what they can do in the portal."
        actions={<Button variant="primary" icon="plus" onClick={() => setOpen(true)}>Add user</Button>} />
      <Card pad={0} style={{ overflow: "hidden" }}>
        <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr 1fr 90px", gap: 12, padding: "13px 22px", background: "var(--bg-mist)", borderBottom: "1px solid var(--border)", fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.8px", textTransform: "uppercase", color: "var(--fg-mute)" }}>
          <span>User</span><span>Role</span><span>Status</span><span></span>
        </div>
        {users.map((u, i) => (
          <div key={u.id} style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr 1fr 90px", gap: 12, padding: "14px 22px", borderTop: i ? "1px solid var(--border)" : "none", alignItems: "center" }}>
            <span style={{ display: "flex", alignItems: "center", gap: 12, minWidth: 0 }}>
              <span style={{ width: 38, height: 38, borderRadius: "50%", background: "var(--brand)", color: "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center", fontWeight: 700, fontSize: 13, flex: "none" }}>{u.initials}</span>
              <span style={{ minWidth: 0 }}>
                <span style={{ display: "block", fontWeight: 600, fontSize: 14, color: "var(--fg-strong)" }}>{u.name}</span>
                <span style={{ display: "block", fontSize: 12.5, color: "var(--fg-mute)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{u.email}</span>
              </span>
            </span>
            <span><Badge tone={roleTone(u.role)}>{u.role}</Badge></span>
            <span><Badge tone={u.status === "Active" ? "success" : "warn"}><StatusDot color={u.status === "Active" ? "#22b86e" : "var(--warn)"} /> {u.status}</Badge></span>
            <span style={{ textAlign: "right" }}>
              <button onClick={() => onRemove(u.id)} style={{ background: "var(--bg-mist)", border: "none", borderRadius: 8, width: 32, height: 32, display: "inline-flex", alignItems: "center", justifyContent: "center", color: "var(--fg-mute)" }}><Icon name="x" size={15} /></button>
            </span>
          </div>
        ))}
      </Card>

      <Modal open={open} onClose={() => setOpen(false)} title="Invite a user" width={480}>
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <Field label="Full name"><TextInput value={name} onChange={setName} placeholder="Jane Smith" /></Field>
          <Field label="Email"><TextInput value={email} onChange={setEmail} placeholder="jane.smith@meridiangroup.com.au" /></Field>
          <Field label="Role" hint="Admin manages billing & users · Booking can place orders · View only can track & view history">
            <Select value={role} onChange={setRole} options={ROLES} />
          </Field>
          <div style={{ display: "flex", gap: 10, marginTop: 4 }}>
            <Button variant="ghost" onClick={() => setOpen(false)}>Cancel</Button>
            <Button variant="primary" full icon="mail" onClick={add} disabled={!name || !email}>Send invite</Button>
          </div>
        </div>
      </Modal>
    </div>
  );
}

Object.assign(window, { Invoices, PaymentMethods, Users });
