// mailroom-domains.jsx — Domains & Mailboxes. Domain cards with attach status +
// mailbox warmup-heat bars, buying-readiness checklist, register/attach drawers,
// top-up modal. Exports: ViewDomains.

const DOMAINS = [
  { domain: "reachgrid.co", attach: "attached", age: "94d", boxes: [
      { e: "mohit@reachgrid.co", warm: 98 }, { e: "growth@reachgrid.co", warm: 95 }, { e: "team@reachgrid.co", warm: 91 } ] },
  { domain: "trygrid.io", attach: "attached", age: "88d", boxes: [
      { e: "mohit@trygrid.io", warm: 93 }, { e: "team@trygrid.io", warm: 90 }, { e: "hello@trygrid.io", warm: 88 } ] },
  { domain: "gridmail.co", attach: "attached", age: "61d", boxes: [
      { e: "mohit@gridmail.co", warm: 72 }, { e: "sales@gridmail.co", warm: 64 }, { e: "hi@gridmail.co", warm: 58 } ] },
  { domain: "growthgrid.co", attach: "warming", age: "12d", stalled: true, boxes: [
      { e: "hello@growthgrid.co", warm: 31 }, { e: "mohit@growthgrid.co", warm: 24 }, { e: "team@growthgrid.co", warm: 0 } ] },
];

function ViewDomains() {
  const t = useT();
  const [register, setRegister] = React.useState(false);
  const [attach, setAttach] = React.useState(false);
  const [topup, setTopup] = React.useState(false);
  const [funded, setFunded] = React.useState(false);
  const [box, setBox] = React.useState(null);

  return (
    <>
      <PageHeader title="Domains & Mailboxes" sub="4 domains · 12 mailboxes · provisioned by Maildoso">
        <Btn kind="soft" icon="server" onClick={() => setAttach(true)}>Attach owned</Btn>
        <Btn kind="primary" icon="globe" onClick={() => setRegister(true)}>Register new</Btn>
      </PageHeader>

      <div style={{ flex: 1, overflowY: "auto", padding: t.pad, display: "flex", flexDirection: "column", gap: t.gap }}>
        {/* buying readiness checklist */}
        <Card>
          <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 14 }}>
            <Icon name="dollar" size={16} color={t.accent} />
            <span style={{ fontFamily: t.head, fontSize: 14.5, fontWeight: 700, color: t.text }}>Domain-buying readiness</span>
            {funded ? <Chip tone="good" icon="check">ready</Chip> : <Chip tone="warn">1 item left</Chip>}
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 10 }}>
            <ReadyItem ok label="Namecheap API connected" sub="verified 2h ago" t={t} />
            <ReadyItem ok label="Registrant contact saved" sub="Mohit Rana · igtre.studio" t={t} />
            <ReadyItem ok={funded} label="Lithic card funded" sub={funded ? "balance $104.20" : "balance $4.20 — top up to buy"}
              action={!funded && <Btn kind="marker" size="sm" icon="dollar" onClick={() => setTopup(true)}>Top up</Btn>} t={t} />
          </div>
        </Card>

        {/* domain cards */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: t.gap }}>
          {DOMAINS.map((d) => {
            const avg = Math.round(d.boxes.reduce((s, b) => s + b.warm, 0) / d.boxes.length);
            return (
              <Card key={d.domain} pad={false} style={{ overflow: "hidden", borderColor: d.stalled ? t.markerBorder : t.border }}>
                <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "14px 16px", borderBottom: `1px solid ${t.border}`,
                  background: d.stalled ? t.markerTint : "transparent" }}>
                  <div style={{ width: 32, height: 32, borderRadius: t.radiusSm, background: t.dark ? t.sunken : t.bg, border: `1px solid ${t.border}`,
                    display: "flex", alignItems: "center", justifyContent: "center", flex: "0 0 auto" }}>
                    <Icon name="globe" size={16} color={d.stalled ? t.warn : t.accent} />
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <Mono style={{ fontSize: 14, fontWeight: 700, color: t.text }}>{d.domain}</Mono>
                    <div style={{ fontSize: 11.5, color: t.textMuted, marginTop: 1 }}>aged {d.age} · 3 mailboxes</div>
                  </div>
                  {d.attach === "attached"
                    ? <StatusChip tone="good">attached</StatusChip>
                    : <StatusChip tone="warn" dotPulse>warming</StatusChip>}
                  <Menu items={[
                    { label: "DNS records", icon: "shield", onClick: () => mrToast(`SPF · DKIM · DMARC all pass for ${d.domain}`, { tone: "good", icon: "shield" }) },
                    { label: "Add mailbox", icon: "plus", onClick: () => mrToast("Maildoso provisioning a mailbox…", { icon: "mail" }) },
                    { label: d.stalled ? "Restart warmup" : "Pause warmup", icon: "flame", onClick: () => mrToast(d.stalled ? "Warmup restarted" : "Warmup paused", { tone: "warn", icon: "flame" }) },
                    { divider: true },
                    { label: "Detach domain", icon: "x", danger: true, onClick: () => mrToast(`Detached ${d.domain}`, { tone: "warn", icon: "x" }) },
                  ]} />
                </div>

                <div style={{ padding: "12px 16px" }}>
                  <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 11 }}>
                    <Label>Mailboxes · warmup heat</Label>
                    <Mono style={{ fontSize: 11.5, fontWeight: 700, color: avg >= 80 ? t.good : avg >= 45 ? t.warn : t.bad }}>avg {avg}</Mono>
                  </div>
                  <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                    {d.boxes.map((b, bi) => (
                      <div key={b.e} onClick={() => setBox({ ...b, domain: d.domain, esp: bi % 2 ? "Microsoft" : "Google", limit: 40, sent: Math.round(b.warm / 100 * 38) })}
                        title="Open mailbox" style={{ display: "flex", alignItems: "center", gap: 10, cursor: "pointer", padding: "3px 4px", margin: "-3px -4px", borderRadius: 4 }}
                        onMouseEnter={(e) => e.currentTarget.style.background = t.dark ? t.sunken : t.bg}
                        onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
                        <Mono style={{ fontSize: 12, color: t.textSec, width: 150, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", flex: "0 0 auto" }}>{b.e}</Mono>
                        <WarmBar val={b.warm} t={t} h={6} />
                        <Mono style={{ fontSize: 11.5, fontWeight: 700, width: 26, textAlign: "right", flex: "0 0 auto",
                          color: b.warm >= 80 ? t.good : b.warm >= 45 ? t.warn : b.warm === 0 ? t.textMuted : t.bad }}>{b.warm}</Mono>
                        <Icon name="chevR" size={13} color={t.textMuted} style={{ flex: "0 0 auto" }} />
                      </div>
                    ))}
                  </div>
                  {d.stalled && (
                    <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 13, padding: "8px 11px", borderRadius: t.radiusSm,
                      background: t.markerTint, border: `1px solid ${t.markerBorder}` }}>
                      <Icon name="alert" size={14} color={t.markerInk} />
                      <span style={{ fontSize: 12, color: t.markerInk, fontWeight: 600 }}>Warmup stalled</span>
                      <button onClick={() => mrToast("Warmup restarted via Maildoso", { tone: "good", icon: "flame" })}
                        style={{ border: "none", background: "transparent", color: t.accentText, fontWeight: 650, fontSize: 12, cursor: "pointer", fontFamily: t.font }}>Restart →</button>
                    </div>
                  )}
                </div>
              </Card>
            );
          })}
        </div>
      </div>

      {/* register new domains drawer */}
      <RegisterDrawer open={register} onClose={() => setRegister(false)} funded={funded} onTopup={() => { setRegister(false); setTopup(true); }} />
      {/* attach owned drawer */}
      <AttachDrawer open={attach} onClose={() => setAttach(false)} />
      {/* mailbox detail drawer */}
      <MailboxDrawer b={box} onClose={() => setBox(null)} />
      {/* top up modal */}
      <Modal open={topup} onClose={() => setTopup(false)} icon="dollar" title="Top up Lithic card"
        sub="Funds the agent's domain purchases. Charged to your default payment method."
        footer={<>
          <Btn kind="ghost" onClick={() => setTopup(false)}>Cancel</Btn>
          <div style={{ flex: 1 }} />
          <Btn kind="primary" icon="check" onClick={() => { setFunded(true); setTopup(false); mrToast("Lithic card funded · +$100.00", { tone: "good", icon: "dollar" }); }}>Add $100.00</Btn>
        </>}>
        <Field label="Amount" value="$100.00" mono onChange={() => {}} />
        <div style={{ display: "flex", gap: 8, marginTop: 12 }}>
          {["$50", "$100", "$250"].map((a, i) => (
            <Chip key={a} tone={i === 1 ? "accent" : "neutral"} mono style={{ padding: "6px 13px", cursor: "pointer" }}>{a}</Chip>
          ))}
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 16, fontSize: 12, color: t.textMuted }}>
          <Icon name="shield" size={14} color={t.textMuted} /> Spend stays under your $100/day cap.
        </div>
      </Modal>
    </>
  );
}

function RegisterDrawer({ open, onClose, funded, onTopup }) {
  const t = useT();
  const cands = [
    { d: "revopsreach.co", price: 11.98, avail: true }, { d: "getrevops.io", price: 13.99, avail: true },
    { d: "revopshq.co", price: 12.98, avail: true }, { d: "revops.email", price: 0, avail: false },
  ];
  const [pick, setPick] = React.useState({ "revopsreach.co": true, "getrevops.io": true });
  const total = cands.filter((c) => pick[c.d] && c.avail).reduce((s, c) => s + c.price, 0);
  const n = Object.values(pick).filter(Boolean).length;
  return (
    <Drawer open={open} onClose={onClose} width={480} title="Register new domains"
      sub="The agent buys these via Namecheap — approval required"
      footer={<>
        <Btn kind="ghost" onClick={onClose}>Cancel</Btn>
        <div style={{ flex: 1 }} />
        {funded
          ? <Btn kind="primary" icon="check" onClick={() => { onClose(); mrToast(`${n} domains registered · $${total.toFixed(2)}`, { tone: "good", icon: "globe" }); }}>Approve & spend ${total.toFixed(2)}</Btn>
          : <Btn kind="marker" icon="dollar" onClick={onTopup}>Top up to buy</Btn>}
      </>}>
      <div style={{ display: "flex", alignItems: "flex-start", gap: 10, padding: "11px 13px", borderRadius: t.radiusSm,
        background: t.accentTint, border: `1px solid ${t.accentBorder}`, marginBottom: 16 }}>
        <Icon name="dollar" size={16} color={t.accent} style={{ marginTop: 1 }} />
        <span style={{ fontSize: 12.5, color: t.accentText, fontWeight: 600 }}>Spends money — charged to your Lithic card on approval.</span>
      </div>
      <Field label="Search a name" value="revops" suffix=".co / .io" onChange={() => {}} style={{ marginBottom: 14 }} />
      <Label style={{ marginBottom: 9 }}>Candidates</Label>
      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        {cands.map((c) => {
          const on = !!pick[c.d];
          return (
            <div key={c.d} onClick={() => c.avail && setPick({ ...pick, [c.d]: !on })} style={{ display: "flex", alignItems: "center", gap: 11,
              padding: "12px 13px", borderRadius: t.radiusSm, cursor: c.avail ? "pointer" : "default", opacity: c.avail ? 1 : 0.5,
              border: `1px solid ${on ? t.accentBorder : t.border}`, background: on ? t.accentTint : t.card }}>
              <span style={{ width: 17, height: 17, borderRadius: 4, border: `1.5px solid ${on ? t.accent : t.borderStrong}`,
                background: on ? t.accent : "transparent", display: "flex", alignItems: "center", justifyContent: "center", flex: "0 0 auto" }}>
                {on && <Icon name="check" size={11} color="#fff" sw={3} />}</span>
              <Mono style={{ fontSize: 13, fontWeight: 600, flex: 1 }}>{c.d}</Mono>
              {c.avail ? <Chip tone="good">available</Chip> : <Chip tone="bad">taken</Chip>}
              <Mono style={{ fontSize: 12.5, fontWeight: 700, color: c.avail ? t.text : t.textMuted, width: 56, textAlign: "right" }}>{c.avail ? "$" + c.price.toFixed(2) : "—"}</Mono>
            </div>
          );
        })}
      </div>
      <div style={{ display: "flex", justifyContent: "space-between", marginTop: 16, padding: "12px 13px", borderRadius: t.radiusSm,
        background: t.sunken, border: `1px solid ${t.border}` }}>
        <span style={{ fontSize: 12.5, color: t.textSec }}>{n} domains · 1 yr · auto-renew off</span>
        <Mono style={{ fontSize: 14, fontWeight: 700, color: t.accent }}>${total.toFixed(2)}</Mono>
      </div>
    </Drawer>
  );
}

function AttachDrawer({ open, onClose }) {
  const t = useT();
  const [val, setVal] = React.useState("");
  return (
    <Drawer open={open} onClose={onClose} width={440} title="Attach an owned domain"
      sub="Point your DNS at Maildoso, then we verify & start warmup"
      footer={<>
        <Btn kind="ghost" onClick={onClose}>Cancel</Btn>
        <div style={{ flex: 1 }} />
        <Btn kind="primary" icon="check" onClick={() => { onClose(); mrToast("Domain queued for verification", { tone: "good", icon: "server" }); }}>Verify & attach</Btn>
      </>}>
      <Field label="Domain" value={val} placeholder="yourdomain.com" mono onChange={setVal} style={{ marginBottom: 16 }} />
      <Label style={{ marginBottom: 9 }}>Add these DNS records</Label>
      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        {[["MX", "mx.maildoso.com"], ["TXT (SPF)", "v=spf1 include:maildoso.com ~all"], ["CNAME", "dkim._domainkey → md.dkim"]].map(([k, v]) => (
          <div key={k} style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 12px", borderRadius: t.radiusSm, background: t.sunken, border: `1px solid ${t.border}` }}>
            <Chip tone="neutral" mono style={{ flex: "0 0 auto" }}>{k}</Chip>
            <Mono style={{ fontSize: 11.5, color: t.textSec, flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{v}</Mono>
            <IconBtn icon="copy" size={14} onClick={() => mrToast("Copied", { icon: "copy" })} />
          </div>
        ))}
      </div>
    </Drawer>
  );
}

function MailboxDrawer({ b, onClose }) {
  const t = useT();
  if (!b) return null;
  const target = b.warm;
  // synth 21-day warmup curve rising toward current heat
  const curve = Array.from({ length: 21 }, (_, i) => Math.max(0, Math.round(target * (0.15 + 0.85 * (i / 20)) + (i % 3 - 1) * 3)));
  const W = 440, H = 90, max = 100;
  const xs = (i) => 4 + (i / (curve.length - 1)) * (W - 8);
  const ys = (v) => H - 8 - (v / max) * (H - 16);
  const line = curve.map((v, i) => `${xs(i)},${ys(v)}`).join(" ");
  const col = target >= 80 ? t.good : target >= 45 ? t.warn : t.bad;
  const stalled = target === 0;
  return (
    <Drawer open={!!b} onClose={onClose} width={460}
      title={<span style={{ fontFamily: t.mono }}>{b.e}</span>}
      sub={`${b.domain} · ${b.esp} · provisioned by Maildoso`}
      footer={<>
        <Btn kind="soft" icon="external" onClick={() => mrToast("Opening inbox in new window…", { icon: "external" })}>Open inbox</Btn>
        <div style={{ flex: 1 }} />
        <Btn kind={stalled ? "primary" : "soft"} icon="flame" onClick={() => mrToast(stalled ? "Warmup restarted" : "Warmup paused", { tone: stalled ? "good" : "warn", icon: "flame" })}>
          {stalled ? "Restart warmup" : "Pause warmup"}</Btn>
      </>}>
      <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 18 }}>
        {stalled ? <StatusChip tone="bad" dotPulse>warmup stalled</StatusChip>
          : target >= 80 ? <StatusChip tone="good">healthy</StatusChip> : <StatusChip tone="warn" dotPulse>warming</StatusChip>}
        <Mono style={{ fontSize: 12, color: t.textMuted }}>heat {target}/100</Mono>
      </div>

      <Label style={{ marginBottom: 10 }}>Warmup curve · 21 days</Label>
      <div style={{ padding: "12px 12px 6px", borderRadius: t.radiusSm, background: t.sunken, border: `1px solid ${t.border}`, marginBottom: 20 }}>
        <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ display: "block" }} preserveAspectRatio="none">
          {[80, 45].map((g) => <line key={g} x1={4} x2={W - 4} y1={ys(g)} y2={ys(g)} stroke={t.border} strokeWidth="1" strokeDasharray="3 4" />)}
          <polyline points={line} fill="none" stroke={col} strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" />
          <circle cx={xs(curve.length - 1)} cy={ys(curve[curve.length - 1])} r="3.5" fill={col} />
        </svg>
      </div>

      <Label style={{ marginBottom: 10 }}>Today</Label>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 8, marginBottom: 20 }}>
        {[["sent", b.sent], ["daily limit", b.limit], ["ESP", b.esp]].map(([l, v], i) => (
          <div key={i} style={{ padding: "11px 12px", borderRadius: t.radiusSm, background: t.sunken, border: `1px solid ${t.border}` }}>
            <Mono style={{ fontSize: 16, fontWeight: 700, color: t.text }}>{v}</Mono>
            <div style={{ fontSize: 10.5, color: t.textMuted, marginTop: 2 }}>{l}</div>
          </div>
        ))}
      </div>

      <Label style={{ marginBottom: 10 }}>Deliverability checks</Label>
      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        {[["SPF", true], ["DKIM", true], ["DMARC", !stalled], ["Not blacklisted", !stalled]].map(([k, ok]) => (
          <div key={k} style={{ display: "flex", alignItems: "center", gap: 9, padding: "9px 12px", borderRadius: t.radiusSm, background: t.card, border: `1px solid ${t.border}` }}>
            <Icon name={ok ? "checkCircle" : "alertCircle"} size={15} color={ok ? t.good : t.warn} />
            <span style={{ fontSize: 12.5, color: t.textSec, flex: 1 }}>{k}</span>
            <Chip tone={ok ? "good" : "warn"}>{ok ? "pass" : "pending"}</Chip>
          </div>
        ))}
      </div>
    </Drawer>
  );
}

function ReadyItem({ ok, label, sub, action, t }) {
  return (
    <div style={{ display: "flex", alignItems: "flex-start", gap: 10, padding: "11px 13px", borderRadius: t.radiusSm,
      border: `1px solid ${ok ? hexA(t.good, 0.3) : t.markerBorder}`, background: ok ? t.goodTint : t.markerTint }}>
      <Icon name={ok ? "checkCircle" : "alertCircle"} size={17} color={ok ? t.good : t.warn} style={{ flex: "0 0 auto", marginTop: 1 }} />
      <div style={{ minWidth: 0, flex: 1 }}>
        <div style={{ fontSize: 12.5, fontWeight: 650, color: t.text }}>{label}</div>
        <div style={{ fontSize: 11.5, color: t.textMuted, marginTop: 2 }}>{sub}</div>
        {action && <div style={{ marginTop: 9 }}>{action}</div>}
      </div>
    </div>
  );
}
window.ViewDomains = ViewDomains;
