// ── Studio — PaintMini dashboard for logged-in user ───────────────

function Studio({ navigate, user, credits, onSignOut, projects, loading, onProjectChanged }) {
  const [query, setQuery] = useState('');
  const [deletingId, setDeletingId] = useState(null);

  async function handleDelete(id) {
    if (!confirm('Delete this project and both schemes? This cannot be undone.')) return;
    setDeletingId(id);
    try {
      await Api.deleteProject(id);
      onProjectChanged && onProjectChanged();
    } catch (err) {
      alert('Failed to delete: ' + err.message);
    } finally {
      setDeletingId(null);
    }
  }

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return projects;
    return projects.filter(p =>
      (p.name || '').toLowerCase().includes(q) ||
      (p.archetype || '').toLowerCase().includes(q)
    );
  }, [projects, query]);

  const searching = query.trim().length > 0;

  // When not searching, surface the 6 most recent; otherwise show every match
  const shown = useMemo(
    () => (searching ? filtered : filtered.slice(0, 6)),
    [filtered, searching]
  );

  // Command-center stats computed from projects + credits
  const stats = useMemo(() => {
    const hours = projects.reduce((s, p) => s + (Number(p.timeHours) || 0), 0);
    return { total: projects.length, hours };
  }, [projects]);

  const lowCredits = typeof credits === 'number' && credits < 1;
  const first = (user?.name || 'painter').split(' ')[0];

  return (
    <div className="pm-shell" data-screen-label="studio">
      <style>{`
        @media (max-width: 640px) { .pm-topbar-search { display: none !important; } }
        .st-hero-thumbs { display: flex; }
        @media (max-width: 760px) { .st-hero-thumbs { display: none !important; } }
      `}</style>
      <PMSidebar navigate={navigate} active="studio" user={user} credits={credits} onSignOut={onSignOut} />

      <div className="pm-content">
        {/* Top bar */}
        <div className="pm-topbar" style={{ flexWrap: 'wrap', gap: 12, rowGap: 12 }}>
          <div style={{ minWidth: 0 }}>
            <div className="pm-h1">Your Studio</div>
            <div className="pm-eyebrow" style={{ marginTop: 3 }}>
              {projects.length} design{projects.length === 1 ? '' : 's'} · {credits ?? 0} credit{credits === 1 ? '' : 's'}
            </div>
          </div>
          <div style={{ flex: 1, minWidth: 16 }} />
          <input
            className="input pm-topbar-search"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder="Search your designs…"
            style={{ height: 36, flex: '1 1 160px', minWidth: 120, maxWidth: 220, fontSize: 13, borderRadius: 7 }}
          />
          <button className="btn btn-gold" onClick={() => navigate('editor')} style={{ height: 36, flexShrink: 0 }}>
            New design&nbsp; <span style={{ fontSize: 16 }}>+</span>
          </button>
        </div>

        {/* Body */}
        <div style={{ padding: 'clamp(16px, 4vw, 28px) clamp(16px, 4vw, 28px) 48px' }}>
          {lowCredits && <LowCreditsBanner navigate={navigate} />}

          <StudioHero first={first} projects={projects} credits={credits} stats={stats} navigate={navigate} />

          {loading && projects.length === 0 ? (
            <div style={{ padding: '70px 0', textAlign: 'center', color: 'var(--ink-3)' }} className="mono">
              LOADING YOUR STUDIO…
            </div>
          ) : projects.length === 0 ? (
            <div style={{ marginTop: 22 }}>
              <EmptyStudio navigate={navigate} />
            </div>
          ) : (
            <>
              <div className="pm-section-head" style={{ marginTop: 30 }}>
                <h2>{searching ? 'Search results' : 'Recent designs'}</h2>
                <div className="rule" />
                {searching ? (
                  <span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>{filtered.length} OF {projects.length}</span>
                ) : projects.length > shown.length ? (
                  <button onClick={() => navigate('library')} className="mono" style={{ fontSize: 11, color: 'var(--brand-deep)', fontWeight: 600 }}>
                    VIEW ALL {projects.length} →
                  </button>
                ) : null}
              </div>

              {searching && filtered.length === 0 ? (
                <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--ink-3)', fontSize: 14 }}>
                  No designs match “{query}”.
                </div>
              ) : (
                <div style={{
                  display: 'grid',
                  gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))',
                  gap: 18,
                }}>
                  {shown.map(p => (
                    <DesignCard
                      key={p.id}
                      project={p}
                      onOpen={() => navigate('result', { projectId: p.id })}
                      onDelete={() => handleDelete(p.id)}
                      deleting={deletingId === p.id}
                    />
                  ))}
                </div>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  );
}

// ── Welcome hero (dark, amber glow) — greeting + primary action + stats ──
function StudioHero({ first, projects, credits, stats, navigate }) {
  const thumbs = projects.filter(p => p.image).slice(0, 3);
  const chips = [
    { value: stats.total, label: 'minis painted' },
    { value: stats.hours ? `${stats.hours}h` : '—', label: 'bench hours' },
    { value: typeof credits === 'number' ? credits : '—', label: 'credits left' },
  ];
  return (
    <div style={{
      position: 'relative', overflow: 'hidden',
      background: 'linear-gradient(125deg, var(--sidebar-2) 0%, var(--sidebar) 62%, #17322601 100%)',
      color: 'var(--sidebar-ink)',
      borderRadius: 'var(--r-lg)',
      boxShadow: '0 22px 46px -30px rgba(20,45,32,0.55)',
      padding: 'clamp(24px, 4vw, 34px)',
      display: 'flex', alignItems: 'center', gap: 28, flexWrap: 'wrap',
    }}>
      {/* warm orange glow over the green card */}
      <div style={{
        position: 'absolute', inset: 0, pointerEvents: 'none',
        background: 'radial-gradient(ellipse 520px 260px at 108% 130%, rgba(242,140,56,0.22), transparent 60%), radial-gradient(ellipse 460px 280px at -6% -25%, rgba(255,255,255,0.06), transparent 60%)',
      }} />
      <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: 4, background: 'linear-gradient(180deg, var(--brand), var(--brand-bright))' }} />
      <div style={{ position: 'relative', flex: '1 1 300px', minWidth: 0 }}>
        <span className="mono" style={{ fontSize: 10, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--brand-bright)' }}>The workbench</span>
        <div style={{ fontFamily: 'var(--serif)', fontWeight: 700, fontSize: 'clamp(30px, 4.5vw, 44px)', lineHeight: 1.02, margin: '8px 0 8px', color: 'var(--sidebar-ink)' }}>
          Welcome back, <em style={{ fontStyle: 'normal', color: 'var(--brand-bright)' }}>{first}</em>.
        </div>
        <p style={{ fontSize: 14.5, color: 'var(--sidebar-ink-2)', maxWidth: 420, lineHeight: 1.5, margin: '0 0 20px' }}>
          Upload a primed mini, pick your paints, and render a finished scheme with a full step-by-step guide.
        </p>
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', marginBottom: 22 }}>
          <button className="btn btn-gold" onClick={() => navigate('editor')} style={{ height: 46 }}>
            Start a new design&nbsp; <span style={{ fontSize: 16 }}>+</span>
          </button>
          <button className="btn" onClick={() => navigate('library')} style={{ height: 46, background: 'transparent', color: 'var(--sidebar-ink)', border: '1.5px solid rgba(250,248,245,0.3)' }}>
            Open library
          </button>
        </div>
        <div style={{ display: 'flex', gap: 24, flexWrap: 'wrap' }}>
          {chips.map(c => (
            <div key={c.label}>
              <div style={{ fontFamily: 'var(--serif)', fontWeight: 700, fontSize: 26, lineHeight: 1, color: 'var(--sidebar-ink)' }}>{c.value}</div>
              <div className="mono" style={{ fontSize: 8.5, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--sidebar-ink-3)', marginTop: 4 }}>{c.label}</div>
            </div>
          ))}
        </div>
      </div>
      {thumbs.length > 0 && (
        <div className="st-hero-thumbs" style={{ position: 'relative', flex: 'none', gap: 0, paddingRight: 8 }}>
          {thumbs.map((p, i) => (
            <div key={p.id} onClick={() => navigate('result', { projectId: p.id })} title={p.name} style={{
              width: 108, height: 140, borderRadius: 10, overflow: 'hidden', cursor: 'pointer',
              border: '3px solid var(--sidebar)', marginLeft: i === 0 ? 0 : -34,
              transform: `rotate(${(i - 1) * 5}deg)`, boxShadow: '0 18px 34px -18px rgba(0,0,0,0.5)',
              background: '#000', transition: 'transform 200ms',
            }}
              onMouseEnter={(e) => { e.currentTarget.style.transform = `rotate(${(i - 1) * 5}deg) translateY(-6px)`; }}
              onMouseLeave={(e) => { e.currentTarget.style.transform = `rotate(${(i - 1) * 5}deg)`; }}>
              <img src={p.image} alt={p.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ── Design card (white) ───────────────────────────────────────────
function DesignCard({ project, onOpen, onDelete, deleting }) {
  const [hover, setHover] = useState(false);
  const p = project;
  return (
    <div
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      onClick={onOpen}
      style={{
        background: 'var(--surface)',
        border: `1px solid ${hover ? 'var(--line-2)' : 'var(--line)'}`,
        borderRadius: 'var(--r-md)',
        overflow: 'hidden',
        cursor: 'pointer',
        transform: hover ? 'translateY(-3px)' : 'none',
        boxShadow: hover ? '0 14px 30px -18px rgba(28,26,23,0.4)' : 'none',
        transition: 'transform 180ms, border-color 180ms, box-shadow 180ms',
        opacity: deleting ? 0.4 : 1,
      }}
    >
      <div style={{ position: 'relative' }}>
        <FigureFrame project={p} height={150} />
        {onDelete && hover && (
          <button
            onClick={(e) => { e.stopPropagation(); onDelete(); }}
            disabled={deleting}
            title="Delete project"
            style={{
              position: 'absolute', top: 10, right: 10,
              width: 28, height: 28, borderRadius: '50%',
              background: 'rgba(246,244,239,0.92)',
              border: '1px solid var(--line-2)',
              color: 'var(--brand-deep)',
              display: 'grid', placeItems: 'center',
              backdropFilter: 'blur(6px)', fontSize: 14, fontWeight: 600,
            }}
          >×</button>
        )}
      </div>
      <div style={{ padding: '11px 14px 14px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 8 }}>
          <div style={{ fontFamily: 'var(--serif)', fontWeight: 600, fontSize: 19, lineHeight: 1 }}>
            {p.name}
          </div>
          <span className="mono" style={{ fontSize: 9, letterSpacing: '0.1em', color: 'var(--ink-3)', whiteSpace: 'nowrap' }}>
            {(p.difficulty || '').toUpperCase()}
          </span>
        </div>
        <div style={{ fontSize: 12, color: 'var(--ink-3)', margin: '4px 0 10px' }}>{p.archetype}</div>
        <SwatchRibbon colours={p.palette} height={6} gap={1} />
      </div>
    </div>
  );
}

// ── Empty state ───────────────────────────────────────────────────
function EmptyStudio({ navigate }) {
  return (
    <div style={{
      border: '1.5px dashed var(--line-2)',
      borderRadius: 'var(--r-lg)',
      padding: '64px 32px',
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16,
      textAlign: 'center',
    }}>
      <div style={{
        width: 56, height: 56, borderRadius: '50%',
        background: 'var(--surface)', border: '1px solid var(--line-2)',
        display: 'grid', placeItems: 'center',
        fontSize: 24, color: 'var(--brand)', fontFamily: 'var(--serif)',
      }}>+</div>
      <div>
        <div style={{ fontFamily: 'var(--serif)', fontSize: 26, fontWeight: 600 }}>No designs yet</div>
        <div style={{ fontSize: 13, color: 'var(--ink-3)', marginTop: 4 }}>
          Upload a miniature photo to render your first painted scheme.
        </div>
      </div>
      <button className="btn btn-gold" onClick={() => navigate('editor')}>
        New design&nbsp; <span style={{ fontSize: 16 }}>+</span>
      </button>
    </div>
  );
}

// ── Stats row (white tiles: big serif numeral + mono label) ───────
function StatsRow({ stats, credits }) {
  const creditLabel = typeof credits === 'number' ? credits : (credits ?? '—');
  const tiles = [
    { label: 'Total minis', value: stats.total, hint: 'schemes complete' },
    { label: 'Credits', value: creditLabel, hint: 'renders left', accent: typeof credits === 'number' && credits < 1 },
  ];
  return (
    <div style={{
      display: 'grid',
      gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))',
      gap: 14,
    }}>
      {tiles.map(t => (
        <StatTile key={t.label} {...t} />
      ))}
    </div>
  );
}

function StatTile({ label, value, hint, accent }) {
  return (
    <div style={{
      background: 'var(--surface)',
      border: `1px solid ${accent ? 'rgba(242,140,56,0.5)' : 'var(--line)'}`,
      borderRadius: 'var(--r-md)',
      padding: '16px 18px',
      position: 'relative',
      overflow: 'hidden',
    }}>
      {accent && (
        <span style={{
          position: 'absolute', top: 0, left: 0, width: 3, height: '100%',
          background: 'var(--brand)',
        }} />
      )}
      <div style={{
        fontFamily: 'var(--serif)', fontWeight: 600,
        fontSize: 38, lineHeight: 1, color: 'var(--ink)',
        letterSpacing: '-0.01em',
      }}>
        {value}
      </div>
      <div className="mono" style={{
        fontSize: 9.5, letterSpacing: '0.14em', textTransform: 'uppercase',
        color: accent ? 'var(--brand-deep)' : 'var(--ink-3)', marginTop: 8,
      }}>
        {label}
      </div>
      <div style={{ fontSize: 11.5, color: 'var(--ink-4)', marginTop: 2 }}>{hint}</div>
    </div>
  );
}

// ── Quick actions ("Jump back in") ────────────────────────────────
function QuickActions({ navigate }) {
  const actions = [
    { to: 'editor',  icon: 'plus',    title: 'New design',      sub: 'Render a fresh scheme',   primary: true },
    { to: 'library', icon: 'library', title: 'Library',         sub: 'Browse every mini' },
    { to: 'paints',  icon: 'paints',  title: 'Paints & collections', sub: 'Manage your ranges' },
    { to: 'credits', icon: 'credits', title: 'Buy credits',     sub: 'Top up your renders' },
  ];
  return (
    <div style={{
      display: 'grid',
      gridTemplateColumns: 'repeat(auto-fill, minmax(210px, 1fr))',
      gap: 14,
    }}>
      {actions.map(a => <QuickAction key={a.to} action={a} navigate={navigate} />)}
    </div>
  );
}

function QuickAction({ action, navigate }) {
  const [hover, setHover] = useState(false);
  const a = action;
  return (
    <button
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      onClick={() => navigate(a.to)}
      style={{
        display: 'flex', alignItems: 'center', gap: 13,
        textAlign: 'left', width: '100%',
        background: a.primary ? 'var(--sidebar)' : 'var(--surface)',
        color: a.primary ? 'var(--sidebar-ink)' : 'var(--ink)',
        border: `1px solid ${a.primary ? 'transparent' : (hover ? 'var(--line-2)' : 'var(--line)')}`,
        borderRadius: 'var(--r-md)',
        padding: '14px 16px',
        cursor: 'pointer',
        transform: hover ? 'translateY(-2px)' : 'none',
        boxShadow: hover ? '0 12px 26px -18px rgba(28,26,23,0.45)' : 'none',
        transition: 'transform 160ms, border-color 160ms, box-shadow 160ms',
      }}
    >
      <span style={{
        flexShrink: 0,
        width: 38, height: 38, borderRadius: '50%',
        display: 'grid', placeItems: 'center',
        background: a.primary ? 'var(--brand)' : 'var(--brand-soft)',
        color: a.primary ? 'var(--sidebar)' : 'var(--brand-deep)',
        border: a.primary ? 'none' : '1px solid rgba(242,140,56,0.35)',
      }}><PMIcon name={a.icon} size={18} /></span>
      <span style={{ minWidth: 0 }}>
        <span style={{
          display: 'block', fontFamily: 'var(--serif)', fontWeight: 600,
          fontSize: 17, lineHeight: 1.1,
        }}>{a.title}</span>
        <span style={{
          display: 'block', fontSize: 11.5, marginTop: 3,
          color: a.primary ? 'var(--sidebar-ink-2)' : 'var(--ink-3)',
        }}>{a.sub}</span>
      </span>
    </button>
  );
}

// ── Low-credits amber nudge ───────────────────────────────────────
function LowCreditsBanner({ navigate }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 14,
      background: 'var(--brand-soft)',
      border: '1px solid rgba(242,140,56,0.45)',
      borderRadius: 'var(--r-md)',
      padding: '12px 16px',
      marginBottom: 22,
    }}>
      <span style={{
        flexShrink: 0, width: 32, height: 32, borderRadius: '50%',
        background: 'var(--brand)', color: 'var(--sidebar)',
        display: 'grid', placeItems: 'center', fontSize: 16, fontWeight: 700,
        fontFamily: 'var(--serif)',
      }}>!</span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontWeight: 600, fontSize: 13.5, color: 'var(--ink)' }}>
          You’re out of render credits
        </div>
        <div style={{ fontSize: 12, color: 'var(--brand-deep)' }}>
          Top up to keep rendering new painted schemes.
        </div>
      </div>
      <button className="btn btn-gold" onClick={() => navigate('credits')} style={{ height: 36, flexShrink: 0 }}>
        Buy credits
      </button>
    </div>
  );
}

Object.assign(window, { Studio });
