// Customer view: the "what's happening now / what's next / when will I hear
// back" contract made visible. Rows are the shared TicketCard (mode=customer),
// so a ticket looks and expands identically here and on the admin board.
const { useState: useStateCD, useEffect: useEffectCD } = React;

function CustomerDashboard({ onNewReport }) {
  const me = (window.NS.session && window.NS.session.identity()) || window.NS.ME;
  const [tickets, setTickets] = useStateCD(() => window.NS.tickets.forReporter(me.email));

  useEffectCD(() => {
    const unsub = window.NS.tickets.subscribe(() => setTickets(window.NS.tickets.forReporter(me.email)));
    window.NS.tickets.refresh(me.email).then(() => setTickets(window.NS.tickets.forReporter(me.email)));
    return unsub;
  }, []);

  const open = tickets.filter((t) => t.statusCategory !== "Done");
  const resolved = tickets.filter((t) => t.statusCategory === "Done");

  return (
    <div>
      <div className="page-head">
        <div className="eyebrow">My tickets</div>
        <h1 className="page-title">Hi {me.name.split(" ")[0]} — here's what we're on</h1>
        <p className="page-sub">Everything you've reported, in plain language. Click any ticket to see its full status and history.</p>
      </div>

      <div className="grid grid-3" style={{ marginBottom: 22 }}>
        <div className="card stat">
          <span className="stat-label">Open</span>
          <span className="stat-value">{open.length}</span>
          <span className="stat-sub">being triaged or worked on</span>
        </div>
        <div className="card stat">
          <span className="stat-label">Resolved</span>
          <span className="stat-value" style={{ color: "var(--good)" }}>{resolved.length}</span>
          <span className="stat-sub">fixed and shipped</span>
        </div>
        <div className="card stat" style={{ justifyContent: "space-between" }}>
          <span className="stat-label">Something new?</span>
          <button className="btn btn-primary" onClick={onNewReport} style={{ alignSelf: "flex-start", marginTop: 6 }}>Report a bug</button>
        </div>
      </div>

      {!tickets.length && (
        <div className="card empty">
          <h3>Nothing reported yet</h3>
          <p>When you report a bug, it'll show up here so you can follow it.</p>
          <button className="btn btn-primary" onClick={onNewReport} style={{ marginTop: 12 }}>Report a bug</button>
        </div>
      )}

      {!!open.length && <TicketSection title="Open" list={open} />}
      {!!resolved.length && <TicketSection title="Resolved" list={resolved} />}
    </div>
  );
}

function TicketSection({ title, list }) {
  return (
    <div style={{ marginBottom: 24 }}>
      <div className="eyebrow" style={{ marginBottom: 10 }}>{title}</div>
      <div className="ticket">
        {list.map((t) => <TicketCard key={t.key} ticket={t} mode="customer" />)}
      </div>
    </div>
  );
}

window.CustomerDashboard = CustomerDashboard;
