/* Studio shell — auth gate, role switch, responsive nav, routing, real data. */
const Sshell = window.SparkleClassicDesignSystem_7a1470;

function navItems(role) {
  const items = [{ id: 'orders', label: 'Orders', icon: 'list' }];
  if (can(role, 'manageTeam') || can(role, 'editRetention')) items.push({ id: 'settings', label: 'Settings', icon: 'sliders' });
  return items;
}

function Sidebar({ role, view, onView }) {
  const { Icon } = Sshell;
  return (
    <nav style={{ width: 210, flex: '0 0 auto', background: 'var(--plum-ink)', color: 'var(--cream)', padding: '18px 12px', display: 'flex', flexDirection: 'column', gap: 4 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '4px 8px 16px' }}>
        <img src="assets/logo/sparkle-star.png" alt="" style={{ height: 28, imageRendering: 'pixelated' }} />
        <span style={{ fontFamily: 'var(--font-pixel)', fontSize: 10, lineHeight: 1.3 }}>SPARKLE<br />STUDIO</span>
      </div>
      {navItems(role).map((it) => (
        <button key={it.id} onClick={() => onView(it.id)} style={{
          display: 'flex', alignItems: 'center', gap: 10, width: '100%', textAlign: 'left', padding: '10px 12px', cursor: 'pointer',
          fontFamily: 'var(--font-body)', fontWeight: 700, fontSize: 14,
          color: view === it.id ? 'var(--plum-ink)' : 'var(--cream)',
          background: view === it.id ? 'var(--cream)' : 'transparent', border: 'none',
          boxShadow: view === it.id ? 'var(--ofx-edges)' : 'none',
        }}>
          <span style={{ fontSize: 18 }}><Icon name={it.icon} /></span>{it.label}
        </button>
      ))}
      <div style={{ marginTop: 'auto', padding: '12px 8px', fontFamily: 'var(--font-body)', fontSize: 12, opacity: 0.7, display: 'flex', alignItems: 'center', gap: 6 }}>
        <Icon name="lock" size={13} /> Photos auto-delete 48h after delivery
      </div>
    </nav>
  );
}

function NarrowNav({ role, view, onView }) {
  const { Icon } = Sshell;
  return (
    <div style={{ display: 'flex', gap: 8, padding: '10px 14px', background: 'var(--plum-ink)', overflowX: 'auto' }}>
      {navItems(role).map((it) => (
        <button key={it.id} onClick={() => onView(it.id)} style={{
          display: 'flex', alignItems: 'center', gap: 7, padding: '7px 12px', cursor: 'pointer', whiteSpace: 'nowrap',
          fontFamily: 'var(--font-body)', fontWeight: 800, fontSize: 13, border: 0, boxShadow: 'var(--ofx-edges)',
          color: view === it.id ? 'var(--plum-ink)' : 'var(--cream)', background: view === it.id ? 'var(--cream)' : 'transparent',
        }}><Icon name={it.icon} size={15} />{it.label}</button>
      ))}
    </div>
  );
}

// Read-only badge of the signed-in role — the role comes from the session, not a toggle.
function RoleBadge({ role }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
      <span style={{ fontFamily: 'var(--font-pixel)', fontSize: 7, color: 'var(--plum-accent)' }}>SIGNED IN AS</span>
      <span style={{ fontFamily: 'var(--font-body)', fontWeight: 800, fontSize: 12, padding: '6px 11px', boxShadow: 'var(--ofx-edges)', background: 'var(--cream-surface)', color: 'var(--plum-ink)' }}>
        {role === 'crp' ? 'Support' : 'Admin'}
      </span>
    </div>
  );
}

function TopBar({ role, attention, narrow, onSignOut }) {
  const { Icon, Avatar, Badge } = Sshell;
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, padding: '12px 18px', borderBottom: '3px solid var(--plum-ink)', background: 'var(--white)', flexWrap: 'wrap' }}>
      {narrow
        ? <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><img src="assets/logo/sparkle-star.png" alt="" style={{ height: 24, imageRendering: 'pixelated' }} /><span className="spk-h2" style={{ fontSize: 15 }}>Studio</span></div>
        : <RoleBadge role={role} />}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        {attention > 0 && <Badge tone="warning" dot>{attention} need attention</Badge>}
        <Avatar name={ROLES[role].who} size="sm" />
        <button onClick={onSignOut} aria-label="Sign out" title="Sign out" style={{ background: 'none', border: 0, color: 'var(--plum-accent)', cursor: 'pointer', display: 'flex' }}><Icon name="logout" /></button>
      </div>
    </div>
  );
}

/* Loads one order's full detail + activity, then renders the fulfillment screen. */
function OrderDetailRoute({ id, role, onBack, onUpdate }) {
  const [data, setData] = React.useState(null); // { order, events } | { error }
  React.useEffect(() => {
    let alive = true;
    setData(null);
    apiFetch(`/api/order?id=${encodeURIComponent(id)}`)
      .then((d) => { if (alive) setData({ order: studioOrderFromApi(d.order), events: d.events || [] }); })
      .catch((e) => { if (alive) setData({ error: e.message }); });
    return () => { alive = false; };
  }, [id]);

  if (!data) return <div className="spk-muted" style={{ padding: 40, textAlign: 'center' }}>Loading order…</div>;
  if (data.error) {
    return (
      <div>
        <button onClick={onBack} style={{ display: 'flex', alignItems: 'center', gap: 6, background: 'none', border: 'none', color: 'var(--plum-accent)', cursor: 'pointer', fontSize: 14, fontWeight: 700, marginBottom: 14, padding: 0 }}>← All orders</button>
        <p style={{ color: 'var(--danger)' }}>Couldn’t load this order: {data.error}</p>
      </div>
    );
  }
  return <OrderDetail order={data.order} events={data.events} wall={data.wall} role={role} onBack={onBack} onUpdate={onUpdate} />;
}

function AdminApp() {
  const narrow = useIsNarrow();
  const [signedIn, setSignedIn] = React.useState(false);
  const [booting, setBooting] = React.useState(true);
  const [role, setRole] = React.useState('admin');
  const [orders, setOrders] = React.useState([]);
  const [loadErr, setLoadErr] = React.useState(null);
  const [view, setView] = React.useState('orders');
  const [openId, setOpenId] = React.useState(null);
  const [crpPerms, setCrpPermsState] = React.useState({});

  const loadOrders = React.useCallback(
    () => apiFetch('/api/orders').then((d) => { setOrders((d.orders || []).map(studioOrderFromApi)); if (d.role) setRole(d.role); setCrpPermsState(d.crpPerms || {}); setCrpOverrides(d.crpPerms || {}); setLoadErr(null); }),
    []
  );

  // On mount: if a session cookie is still valid, /api/orders succeeds and we skip sign in.
  React.useEffect(() => {
    let alive = true;
    apiFetch('/api/orders')
      .then((d) => { if (!alive) return; setOrders((d.orders || []).map(studioOrderFromApi)); if (d.role) setRole(d.role); setCrpPermsState(d.crpPerms || {}); setCrpOverrides(d.crpPerms || {}); setSignedIn(true); })
      .catch(() => {})
      .finally(() => { if (alive) setBooting(false); });
    return () => { alive = false; };
  }, []);

  if (booting) return <div style={{ minHeight: '70vh', display: 'flex', alignItems: 'center', justifyContent: 'center' }} className="spk-muted">Loading…</div>;
  if (!signedIn) return <SignIn onSignedIn={() => { setSignedIn(true); loadOrders().catch((e) => setLoadErr(e.message)); }} />;

  const signOut = () => {
    fetch('/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'same-origin', body: JSON.stringify({ action: 'logout' }) })
      .finally(() => { setSignedIn(false); setOrders([]); setOpenId(null); });
  };
  const goView = (v) => { setView(v); setOpenId(null); };
  const update = (id, patch) => setOrders((os) => os.map((o) => o.id === id ? { ...o, ...patch } : o));
  const attention = orders.filter((o) => o.status === 'action').length;

  return (
    <div style={{ display: 'flex', flexDirection: narrow ? 'column' : 'row', minHeight: 680, background: 'var(--cream-surface)', overflow: 'hidden', boxShadow: 'var(--ofx-edges), var(--shadow-block-lg)' }}>
      {!narrow && <Sidebar role={role} view={view} onView={goView} />}
      <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column' }}>
        <TopBar role={role} attention={attention} narrow={narrow} onSignOut={signOut} />
        {narrow && <NarrowNav role={role} view={view} onView={goView} />}
        {narrow && <div style={{ padding: '10px 14px 0' }}><RoleBadge role={role} /></div>}
        <div style={{ padding: narrow ? 14 : 22, overflow: 'auto', flex: 1 }}>
          {openId ? (
            <OrderDetailRoute id={openId} role={role} onBack={() => { setOpenId(null); loadOrders().catch(() => {}); }} onUpdate={update} />
          ) : view === 'settings' ? (
            <SettingsScreen orders={orders} role={role} crpPerms={crpPerms} onCrpPerms={(p) => { setCrpPermsState(p); setCrpOverrides(p); }} />
          ) : (
            <React.Fragment>
              {loadErr && <div style={{ marginBottom: 12, color: 'var(--danger)', fontSize: 13, fontWeight: 700 }}>Couldn’t refresh orders: {loadErr}</div>}
              <OrdersList orders={orders} onOpen={(o) => setOpenId(o.id)} />
            </React.Fragment>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { AdminApp });
