// Screen 2: Dashboard Shell — header + role-aware tabs.
const { useState: useStateDS } = React;

function relativeTime(iso) {
  if (!iso) return null;
  const diff = Date.now() - new Date(iso).getTime();
  if (diff < 60000) return 'just now';
  if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}h ago`;
  return `${Math.floor(diff / 86400000)}d ago`;
}

const TABS_BY_ROLE = {
  worker: ["QUEUE", "INVENTORY", "MY STATS"],
  manager: ["QUEUE", "INVENTORY", "STATS", "POs"],
  admin: ["QUEUE", "INVENTORY", "STATS", "POs", "SETTINGS", "BOM EDITOR"],
};

function DashboardShell({ user, onLogout, onStartWO, onResume, initialTab }) {
  const tabs = TABS_BY_ROLE[user.role] || TABS_BY_ROLE.worker;
  const [tab, setTab] = useStateDS(initialTab && tabs.includes(initialTab) ? initialTab : tabs[0]);

  return (
    <div className="min-h-screen bg-zinc-950 text-zinc-100 flex flex-col relative">
      <window.TopStripe />
      {/* Header */}
      <header className="border-b border-zinc-800 bg-zinc-900/40 px-8 pt-5 pb-0 flex flex-col gap-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-4">
            <window.BrandMark size={40} />
            <window.BrandWordmark
              subtitle={user.role === "admin" ? "Admin Console" : user.role === "manager" ? "Floor Manager" : null}
              subtitleColor={user.role === "worker" ? "#71717a" : window.GPS_RED}
            />
          </div>
          <div className="flex items-center gap-4">
            {(() => {
              const shopifyTs = window.SHOPIFY_LAST_SYNC;
              const ssTs = window.SHIPSTATION_LAST_TEST;
              if (!shopifyTs && !ssTs) {
                return (
                  <div className="text-[13px] text-zinc-500 flex items-center gap-2">
                    <span className="h-2 w-2 rounded-full bg-zinc-600 inline-block" />
                    Integrations not connected
                  </div>
                );
              }
              return (
                <div className="text-[13px] text-zinc-400 flex flex-col items-end gap-0.5">
                  {shopifyTs && (
                    <span className="flex items-center gap-1.5">
                      <span className="h-2 w-2 rounded-full bg-emerald-500 inline-block" />
                      Shopify synced {relativeTime(shopifyTs)}
                    </span>
                  )}
                  {ssTs && (
                    <span className="flex items-center gap-1.5">
                      <span className="h-2 w-2 rounded-full bg-emerald-500 inline-block" />
                      ShipStation OK {relativeTime(ssTs)}
                    </span>
                  )}
                </div>
              );
            })()}
            <div className="text-right leading-tight">
              <div className="text-[17px] font-semibold">{user.name}</div>
              <div className="text-[12px] text-zinc-500 flex items-center justify-end gap-2">
                <window.RoleBadge role={user.role} />
                <span>{user.shift}</span>
              </div>
            </div>
            <window.Avatar user={user} size={48} />
            <button onClick={onLogout}
              className="h-12 px-5 rounded-lg bg-zinc-800 border border-zinc-700 text-zinc-200 text-[14px] font-medium hover:bg-zinc-700 uppercase tracking-wider">
              End session
            </button>
          </div>
        </div>

        {/* Tabs */}
        <div className="flex gap-1">
          {tabs.map((t) => {
            const active = t === tab;
            return (
              <button key={t} onClick={() => setTab(t)}
                className={`relative h-12 px-6 font-display text-[18px] tracking-wider transition ${
                  active ? "text-zinc-100" : "text-zinc-500 hover:text-zinc-300"
                }`}>
                {t}
                {active && <div className="absolute bottom-0 left-3 right-3 h-[2px]" style={{ background: window.GPS_RED }} />}
              </button>
            );
          })}
        </div>
      </header>

      {/* Tab content */}
      <main className="flex-1 flex flex-col">
        {tab === "QUEUE" && <window.QueueTab user={user} onStartWO={onStartWO} onResume={onResume} />}
        {tab === "MY STATS" && <window.StatsTab user={user} mode="my" />}
        {tab === "INVENTORY" && (user.role === "worker"
          ? <window.WorkerInventoryTab user={user} />
          : <window.InventoryTab user={user} />)}
        {tab === "STATS" && <window.StatsTab user={user} mode="full" />}
        {tab === "POs" && <window.POsTab user={user} />}
        {tab === "SETTINGS" && <window.SettingsTab user={user} />}
        {tab === "BOM EDITOR" && (
          <iframe src="/bom-editor" className="flex-1 w-full border-0" style={{ height: 'calc(100vh - 140px)' }} />
        )}
      </main>
    </div>
  );
}

window.DashboardShell = DashboardShell;
