const { useState, useEffect } = React;

/* CRM · Sent — global outbound email log for the signed-in user (crm_emails).
 * Real rows only; delivery status + open tracking. Wrapped in CrmShell. */

function SentEmails({ go }) {
  const c = window.ContactIQ && window.ContactIQ.client;
  const [rows, setRows] = useState(null);
  const [orgs, setOrgs] = useState({});

  useEffect(() => {
    if (!c) { setRows([]); return; }
    c.from("crm_emails").select("id,to_email,subject,status,open_count,org_id,sent_at").eq("direction", "out").order("sent_at", { ascending: false }).limit(200)
      .then(async ({ data }) => {
        const list = data || [];
        setRows(list);
        const ids = [...new Set(list.map((e) => e.org_id).filter(Boolean))];
        if (ids.length) {
          const { data: os } = await c.from("organizations").select("id,canonical_name").in("id", ids);
          const m = {}; (os || []).forEach((o) => { m[o.id] = o.canonical_name; }); setOrgs(m);
        }
      }).catch(() => setRows([]));
  }, []);

  const dt = (s) => { try { return new Date(s).toLocaleString(); } catch { return ""; } };
  const opened = rows ? rows.filter((e) => e.open_count > 0).length : 0;

  return (
    <div className="page">
      <div className="page-head" style={{ marginBottom: "16px" }}>
        <div className="ph-text">
          <div className="eyebrow">Outbound email</div>
          <h1 className="page-title">Sent</h1>
          <div className="page-sub">Every email you've sent from the CRM — delivery + open tracking{rows && rows.length ? "  ·  " + rows.length + " sent · " + opened + " opened" : ""}</div>
        </div>
      </div>
      <div className="inbox">
        {rows && rows.map((e) => (
          <div className="sig-row" key={e.id}>
            <div className="sig-col-main">
              <div className="sr-addr"><span className="a">{e.subject || "(no subject)"}</span></div>
              <div className="sr-fact">→ {e.to_email}{e.org_id && orgs[e.org_id] ? "  ·  " + orgs[e.org_id] : ""}</div>
            </div>
            <div className="sig-col-prov">
              <span className="src">{dt(e.sent_at)}</span>
            </div>
            <div className="sig-col-action">
              <span className="pill" style={{ color: e.status === "sent" ? "var(--green)" : e.status === "failed" ? "var(--red)" : "var(--fg-3)" }}>{e.status}</span>
              {e.open_count > 0 && <span className="pill" style={{ marginLeft: 6, color: "var(--accent)" }}>opened</span>}
            </div>
          </div>
        ))}
        {rows && !rows.length && <div className="muted" style={{ padding: "28px", textAlign: "center", fontSize: "var(--fs-base)" }}>No sent email yet. Open a company, reveal a contact, and click <strong>Email</strong>.</div>}
        {!rows && <div className="muted" style={{ padding: "28px", textAlign: "center" }}>Loading…</div>}
      </div>
    </div>
  );
}

function CrmEmailsPage({ go, user }) {
  return <window.CrmShell go={go} user={user} current="emails"><SentEmails go={go} /></window.CrmShell>;
}
window.CrmEmailsPage = CrmEmailsPage;
