// Nexa — dashboard shell.
// Calls TC_API.init() on mount to resolve identity from the session cookie.
// Redirects to /customer/login if the session is missing or expired.

const { NAV } = window.TC_HELPERS;
const { SideIcon, LoadingBlock, ErrorBlock } = window.TC_UI;
const { useFetch, normAgent } = window.TC_HELPERS;
const { OverviewPage, TransactionsPage, BeneficiariesPage, DocumentsPage } = window.TC_PAGES_A;
const { PoliciesPage, AgentsPage } = window.TC_PAGES_B;

function NotificationBell({ principalId }) {
  const [open, setOpen] = useState(false);
  const [notifs, setNotifs] = useState([]);
  const [unread, setUnread] = useState(0);
  const [loading, setLoading] = useState(false);

  function load() {
    if (!principalId) return;
    setLoading(true);
    TC_API.getNotifications()
      .then(r => {
        setNotifs(r.notifications || []);
        setUnread(r.unread_count || 0);
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }

  useEffect(() => {
    load();
    const t = setInterval(load, 30000);
    return () => clearInterval(t);
  }, [principalId]);

  function toggle() {
    if (!open) load();
    setOpen(v => !v);
  }

  function markRead(id) {
    TC_API.markNotificationRead(id)
      .then(() => {
        setNotifs(ns => ns.map(n => n.notification_id === id ? { ...n, read_at: new Date().toISOString() } : n));
        setUnread(u => Math.max(0, u - 1));
      })
      .catch(() => {});
  }

  function markAllRead() {
    TC_API.markAllNotificationsRead()
      .then(() => {
        setNotifs(ns => ns.map(n => ({ ...n, read_at: n.read_at || new Date().toISOString() })));
        setUnread(0);
      })
      .catch(() => {});
  }

  const TYPE_LABELS = {
    approval_needed:    "Approval needed",
    beneficiary_review: "Beneficiary review",
    rfi_created:        "Information request",
    agent_suspended:    "Agent suspended",
    activation_reminder:"Activation reminder",
  };

  return (
    <div className="tc-notif-wrap">
      <button
        className={`tc-notif-bell ${unread > 0 ? "has-unread" : ""}`}
        onClick={toggle}
        title="Notifications"
        aria-label={`Notifications${unread > 0 ? `, ${unread} unread` : ""}`}
      >
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/>
          <path d="M13.73 21a2 2 0 0 1-3.46 0"/>
        </svg>
        {unread > 0 && <span className="tc-notif-badge">{unread > 99 ? "99+" : unread}</span>}
      </button>

      {open && (
        <div className="tc-notif-panel">
          <div className="tc-notif-panel-head">
            <span className="tc-notif-panel-title">Notifications</span>
            {unread > 0 && (
              <button className="tc-notif-mark-all" onClick={markAllRead}>Mark all read</button>
            )}
          </div>

          <div className="tc-notif-list">
            {loading && notifs.length === 0 && (
              <div className="tc-notif-empty">Loading…</div>
            )}
            {!loading && notifs.length === 0 && (
              <div className="tc-notif-empty">No notifications yet.</div>
            )}
            {notifs.map(n => (
              <div
                key={n.notification_id}
                className={`tc-notif-item ${!n.read_at ? "is-unread" : ""}`}
                onClick={() => { if (!n.read_at) markRead(n.notification_id); }}
              >
                <div className="tc-notif-item-head">
                  <span className="tc-notif-type">{TYPE_LABELS[n.type] || n.type}</span>
                  {!n.read_at && <span className="tc-notif-dot" />}
                </div>
                <div className="tc-notif-item-title">{n.title}</div>
                <div className="tc-notif-item-msg">{n.message}</div>
                <div className="tc-notif-item-time">
                  {new Date(n.created_at).toLocaleString("en-GB", { day: "2-digit", month: "short", hour: "2-digit", minute: "2-digit" })}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

function Dashboard() {
  const [session, setSession] = useState(null);  // null = loading, false = unauthed, obj = ready
  const [page, setPage] = useState("overview");
  const [pendingCount, setPendingCount] = useState(0);

  useEffect(() => {
    TC_API.init()
      .then(me => {
        setSession(me);
      })
      .catch(err => {
        if (err.status === 401) {
          window.location.href = "/customer/login";
        } else {
          setSession(false);
        }
      });
  }, []);

  if (session === null) {
    return (
      <div style={{ display: "flex", alignItems: "center", justifyContent: "center", minHeight: "100vh" }}>
        <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 16 }}>
          <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="var(--accent)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
            <path d="M21 12a9 9 0 1 1-6.219-8.56"/>
          </svg>
          <span style={{ fontSize: 13, color: "var(--fg-3)" }}>Loading…</span>
        </div>
      </div>
    );
  }

  if (session === false) {
    return (
      <div style={{ display: "flex", alignItems: "center", justifyContent: "center", minHeight: "100vh" }}>
        <div style={{ textAlign: "center", color: "var(--fg-3)" }}>
          <p>Unable to load session. <a href="/customer/login">Sign in again</a></p>
        </div>
      </div>
    );
  }

  // Shared: agent list (used by Overview agent tags, Policies dropdown, Agents page).
  const agentsQ = useFetch(() => TC_API.getAgents(), [], { polling: 60000 });
  const agents = useMemo(() => (agentsQ.data || []).map(normAgent), [agentsQ.data]);

  const today = useMemo(
    () => new Date().toLocaleDateString("en-GB", { day: "2-digit", month: "short", year: "numeric" }),
    []
  );

  const displayName = session.full_name || session.email || "Account";
  const initials = displayName.split(" ").map(w => w[0]).join("").slice(0, 2).toUpperCase();

  const pageTitle = {
    overview:      { eyebrow: "Treasury overview",                  h: "Overview" },
    transactions:  { eyebrow: "All instructions",                   h: "Transactions" },
    beneficiaries: { eyebrow: "Approved counterparties",            h: "Beneficiaries" },
    documents:     { eyebrow: "Compliance documents",               h: "Documents" },
    policies:      { eyebrow: "Policy guardrails per agent",        h: "Policies" },
    agents:        { eyebrow: `${agents.length} registered · ${agents.filter(a => a.status === "active").length} active`, h: "Agents" },
  }[page] || { eyebrow: "", h: "" };

  return (
    <div className="tc-shell">
      <aside className="tc-side">
        <div className="tc-side-brand">
          <a href="/" className="tc-side-brand-mark" title="Back to Nexa">
            <Icon name="logo" />
            <span>tenor</span>
          </a>
          <span className="tc-side-brand-product">CORE</span>
        </div>

        <div className="tc-side-org">
          <span className="tc-org-k">ORGANISATION</span>
          <span className="tc-org-v">{TC_API.BUSINESS_ID}</span>
        </div>

        <nav className="tc-side-nav" aria-label="Primary">
          <span className="tc-side-nav-h">Treasury</span>
          {NAV.map(n => {
            const count = n.id === "overview" ? pendingCount : null;
            const isAlert = n.id === "overview" && pendingCount > 0;
            return (
              <button
                key={n.id}
                className={`tc-nav-item ${page === n.id ? "is-active" : ""} ${isAlert ? "is-alert" : ""}`}
                onClick={() => setPage(n.id)}
              >
                <SideIcon name={n.id} />
                <span>{n.label}</span>
                {count != null && count > 0
                  ? <span className="tc-nav-item-count">{count}</span>
                  : <span></span>}
              </button>
            );
          })}
        </nav>

        <div className="tc-side-foot">
          <div className="tc-side-avatar">{initials}</div>
          <div style={{display:"flex",flexDirection:"column",gap:1,flex:1,minWidth:0}}>
            <span className="tc-side-foot-l">{displayName}</span>
            <span className="tc-side-foot-s" title={session.email}>{session.email}</span>
          </div>
          <button
            className="tc-btn tc-btn-ghost tc-btn-sm"
            title="Sign out"
            onClick={() => TC_API.logout()}
          >
            Sign out
          </button>
        </div>
      </aside>

      <div className="tc-main">
        <header className="tc-topbar">
          <div className="tc-topbar-l">
            <span className="tc-topbar-eyebrow">{pageTitle.eyebrow}</span>
            <span className="tc-topbar-h">{pageTitle.h}</span>
          </div>
          <div className="tc-topbar-r">
            <NotificationBell principalId={session.principal_id} />
            <span className="tc-status-pill">
              <span className="tc-status-pill-dot" />
              Live · {today}
            </span>
          </div>
        </header>

        {page === "overview"      && <OverviewPage      agents={agents} onNavigate={setPage} onPendingCount={setPendingCount} />}
        {page === "transactions"  && <TransactionsPage  agents={agents} />}
        {page === "beneficiaries" && <BeneficiariesPage />}
        {page === "documents"     && <DocumentsPage />}
        {page === "policies"      && <PoliciesPage      agents={agents} />}
        {page === "agents"        && <AgentsPage        agents={agents} agentsQ={agentsQ} />}
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<Dashboard />);
