// Saved & Studio screens — backed by Supabase when configured,
// localStorage + mock orders when not.

function SavedScreen({ savedIds, toggleSave, onOpenArtwork, artworks }) {
  const items = (artworks || []).filter((a) => savedIds.has(a.id));
  return (
    <>
      <AppHeader title="Saved"/>
      <div style={{ padding: '16px 20px 24px' }}>
        {items.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '60px 20px' }}>
            <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 20 }}>
              <Disk size={64}>888</Disk>
            </div>
            <h3 style={{ margin: 0, fontFamily: 'var(--font-display)', fontSize: 20, color: 'var(--fg)', fontWeight: 500 }}>Nothing saved yet.</h3>
            <p style={{ margin: '8px 0 0', fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 14, color: 'var(--fg-muted)' }}>
              When something catches your eye, tap the ring.
            </p>
          </div>
        ) : (
          <>
            <Eyebrow style={{ marginBottom: 12 }}>{items.length} piece{items.length !== 1 && 's'}</Eyebrow>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              {items.map(a => (
                <div key={a.id} onClick={() => onOpenArtwork(a)} style={{ cursor: 'pointer' }}>
                  <ArtworkFrame image={a.image_url} gradient={a.grad} alt={`${a.title} — ${a.artist}`} saved={true} onSave={() => toggleSave(a.id)}/>
                  <div style={{ padding: '10px 2px 0' }}>
                    <div style={{ fontFamily: 'var(--font-display)', fontSize: 14, fontWeight: 500, color: 'var(--fg)' }}>{a.title}</div>
                    <div style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 11, color: 'var(--fg-muted)' }}>— {a.artist}</div>
                  </div>
                </div>
              ))}
            </div>
          </>
        )}
      </div>
    </>
  );
}

function StudioScreen({ user, onSignIn, onSignOut }) {
  const [orders, setOrders] = React.useState(null);
  const [error, setError] = React.useState(null);

  React.useEffect(() => {
    if (!user || !window.api?.hasBackend) { setOrders([]); return; }
    let alive = true;
    window.api.listOrders()
      .then((rows) => { if (alive) setOrders(rows); })
      .catch((err) => { if (alive) { setError(err.message); setOrders([]); } });
    return () => { alive = false; };
  }, [user]);

  const initial = (user?.email?.[0] || 'M').toUpperCase();
  const sinceMonth = user?.created_at
    ? new Date(user.created_at).toLocaleString('en-US', { month: 'long' })
    : 'October';

  return (
    <>
      <AppHeader title="Studio"/>
      <div style={{ padding: '20px' }}>
        {/* Account header */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '16px 0' }}>
          <Disk size={56}>{initial}</Disk>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 20, fontWeight: 500, color: 'var(--fg)' }}>
              {user?.email || 'Guest'}
            </div>
            <div style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 13, color: 'var(--fg-muted)' }}>
              {user ? `— collecting since ${sinceMonth}` : '— not signed in yet'}
            </div>
          </div>
        </div>

        {!user && (
          <div style={{ padding: 16, background: 'var(--bg-elevated)', borderRadius: 'var(--r-md)', border: '1px solid var(--line)', marginTop: 4 }}>
            <p style={{ margin: '0 0 12px', fontFamily: 'var(--font-display)', fontSize: 14, color: 'var(--fg-soft)', lineHeight: 1.5 }}>
              Sign in to sync your saves across devices and to keep a record of orders.
            </p>
            <Button variant="primary" full onClick={onSignIn} iconRight="arrowRight">Sign in</Button>
          </div>
        )}

        {/* Current commission — kept as a static demo until the commission flow writes to DB */}
        {user && (
          <div style={{ padding: 16, background: 'var(--surface-ink)', color: 'var(--fg-on-ink)', borderRadius: 'var(--r-md)', marginTop: 10 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
              <div style={{ fontFamily: 'var(--font-body)', fontSize: 10, letterSpacing: '0.18em', color: 'var(--fg-on-ink-muted)' }}>IN PROGRESS</div>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--fg-on-ink-muted)' }}>DAY 3 OF 8</div>
            </div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, color: 'var(--fg-on-ink)' }}>Morning light for the nook</div>
            <div style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 13, color: 'var(--fg-on-ink-muted)', marginTop: 4 }}>— Yui Nakamura · first sketch Tuesday</div>
            <div style={{ marginTop: 12, height: 2, background: 'rgba(255,255,255,0.14)', borderRadius: 2, overflow: 'hidden' }}>
              <div style={{ width: '38%', height: '100%', background: 'var(--lucky-500)' }}/>
            </div>
          </div>
        )}

        {/* Orders */}
        <div style={{ marginTop: 24 }}>
          <Eyebrow style={{ marginBottom: 12 }}>Recent orders</Eyebrow>

          {orders === null && (
            <div style={{ padding: '20px 0', fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 13, color: 'var(--fg-muted)' }}>
              Pulling your receipts…
            </div>
          )}

          {orders !== null && orders.length === 0 && (
            <div style={{ padding: '14px 0', fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 13, color: 'var(--fg-muted)' }}>
              {user ? 'No orders yet. The first one always feels like a small ceremony.' : 'Sign in to see your orders.'}
            </div>
          )}

          {orders !== null && orders.map((o) => {
            const firstItem = o.order_items?.[0];
            const dateLabel = o.paid_at
              ? `Paid ${new Date(o.paid_at).toLocaleString('en-US', { month: 'short', day: 'numeric' })}`
              : `Placed ${new Date(o.created_at).toLocaleString('en-US', { month: 'short', day: 'numeric' })}`;
            return (
              <div key={o.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '14px 0', borderBottom: '1px solid var(--line)' }}>
                <div>
                  <div style={{ fontFamily: 'var(--font-display)', fontSize: 15, fontWeight: 500, color: 'var(--fg)' }}>
                    {firstItem ? firstItem.title_snapshot : 'Order'}
                  </div>
                  <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-faint)', marginTop: 3 }}>
                    #{o.short_id} · {dateLabel} · {o.status}
                  </div>
                </div>
                <div style={{ fontFamily: 'var(--font-display)', fontSize: 15, color: 'var(--fg)' }}>
                  {window.api.formatPrice(o.total_cents, o.currency)}
                </div>
              </div>
            );
          })}

          {error && (
            <div style={{ padding: '12px 0', fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--accent)' }}>{error}</div>
          )}
        </div>

        {/* Settings */}
        <div style={{ marginTop: 24 }}>
          <Eyebrow style={{ marginBottom: 4 }}>Settings</Eyebrow>
          {[
            'Shipping addresses',
            'Payment',
            'Notifications',
            'Gift wrap preferences',
          ].map(s => (
            <button key={s} style={{
              width: '100%', padding: '16px 0', display: 'flex', justifyContent: 'space-between', alignItems: 'center',
              background: 'none', border: 'none', borderBottom: '1px solid var(--line)', cursor: 'pointer',
              fontFamily: 'var(--font-body)', fontSize: 14, color: 'var(--fg)', textAlign: 'left',
            }}>
              {s}
              <Icon name="arrowRight" size={16} color="var(--fg-faint)"/>
            </button>
          ))}
          {user && (
            <button onClick={onSignOut} style={{
              width: '100%', padding: '16px 0', display: 'flex', justifyContent: 'space-between', alignItems: 'center',
              background: 'none', border: 'none', borderBottom: '1px solid var(--line)', cursor: 'pointer',
              fontFamily: 'var(--font-body)', fontSize: 14, color: 'var(--accent)', textAlign: 'left',
            }}>
              Sign out
              <Icon name="arrowRight" size={16} color="var(--fg-faint)"/>
            </button>
          )}
        </div>
      </div>
    </>
  );
}

window.SavedScreen = SavedScreen;
window.StudioScreen = StudioScreen;
