// ── Library — trophy shelf of finished (converted) miniatures ───────

function Library({ navigate, user, credits, onSignOut, projects, loading, onProjectChanged }) {
  const [deletingId, setDeletingId] = useState(null);
  const [confirmId, setConfirmId] = useState(null); // project pending delete-confirm

  useEffect(() => { injectLibraryStyles(); }, []);

  const confirmProject = confirmId ? projects.find(p => p.id === confirmId) : null;

  async function confirmDelete() {
    const id = confirmId;
    if (!id) return;
    setDeletingId(id);
    try {
      await Api.deleteProject(id);
      onProjectChanged && onProjectChanged();
      setConfirmId(null);
    } catch (err) {
      alert('Failed to delete: ' + err.message);
    } finally {
      setDeletingId(null);
    }
  }

  return (
    <div data-screen-label="library" className="pm-shell">
      <PMSidebar navigate={navigate} active="library" user={user} credits={credits} onSignOut={onSignOut} />

      <div className="pm-content">
        {/* Top bar */}
        <div className="pm-topbar" style={{ flexWrap: 'wrap', gap: 12 }}>
          <div>
            <div className="pm-h1">Library</div>
            <div className="pm-eyebrow" style={{ marginTop: 3 }}>
              {projects.length} {projects.length === 1 ? 'design' : 'designs'}
            </div>
          </div>
          <div style={{ flex: 1 }} />
        </div>

        {/* Body */}
        <div style={{ padding: 'clamp(16px, 4vw, 24px) clamp(16px, 4vw, 28px) 52px' }}>
          {loading && projects.length === 0 ? (
            <LibraryGrid>
              {Array.from({ length: 8 }).map((_, i) => <SkeletonCard key={i} />)}
            </LibraryGrid>
          ) : projects.length === 0 ? (
            <EmptyLibrary navigate={navigate} />
          ) : (
            <LibraryGrid>
              {projects.map(p => (
                <TrophyCard
                  key={p.id}
                  project={p}
                  deleting={deletingId === p.id}
                  onOpen={() => navigate('result', { projectId: p.id })}
                  onDelete={() => setConfirmId(p.id)}
                />
              ))}
            </LibraryGrid>
          )}
        </div>
      </div>

      {confirmProject && (
        <LibraryConfirm
          name={confirmProject.name || 'this design'}
          busy={deletingId === confirmProject.id}
          onCancel={() => setConfirmId(null)}
          onConfirm={confirmDelete}
        />
      )}
    </div>
  );
}

// ── Delete confirmation modal ──────────────────────────────────────
function LibraryConfirm({ name, busy, onCancel, onConfirm }) {
  useEffect(() => {
    function onKey(e) { if (e.key === 'Escape' && !busy) onCancel(); }
    document.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => { document.removeEventListener('keydown', onKey); document.body.style.overflow = ''; };
  }, [busy]);
  return (
    <div onClick={() => !busy && onCancel()} style={{
      position: 'fixed', inset: 0, zIndex: 200,
      background: 'rgba(28,26,23,0.45)', backdropFilter: 'blur(3px)',
      display: 'grid', placeItems: 'center', padding: 20,
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: '100%', maxWidth: 420, background: 'var(--surface)', color: 'var(--ink)',
        border: '1px solid var(--line)', borderRadius: 16,
        boxShadow: '0 40px 80px -24px rgba(28,26,23,0.5)', padding: '26px 26px 22px',
      }}>
        <div style={{
          width: 44, height: 44, borderRadius: 12, marginBottom: 16,
          background: 'rgba(154,27,31,.10)', border: '1px solid rgba(154,27,31,.28)',
          display: 'grid', placeItems: 'center', color: 'var(--crimson)',
        }}><PMIcon name="trash" size={20} /></div>
        <h2 className="display" style={{ fontSize: 26, marginBottom: 8 }}>Remove <em>{name}</em>?</h2>
        <p style={{ color: 'var(--ink-2)', fontSize: 14, lineHeight: 1.55, margin: '0 0 22px' }}>
          This permanently deletes the design and its painting schemes. This cannot be undone.
        </p>
        <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
          <button className="btn btn-ghost" onClick={onCancel} disabled={busy}>Cancel</button>
          <button className="btn" style={{ background: 'var(--crimson)', color: '#fff' }} onClick={onConfirm} disabled={busy}>
            {busy ? 'Deleting…' : 'Delete design'}
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Responsive grid wrapper ────────────────────────────────────────
function LibraryGrid({ children }) {
  return (
    <div style={{
      display: 'grid',
      gridTemplateColumns: 'repeat(auto-fill, minmax(230px, 1fr))',
      gap: 18,
    }}>
      {children}
    </div>
  );
}

// ── The portrait trophy card ───────────────────────────────────────
function TrophyCard({ project, onOpen, onDelete, deleting }) {
  const [hover, setHover] = useState(false);
  const p = project;
  const meta = [
    p.difficulty,
    (p.timeHours != null ? `${p.timeHours}h` : null),
    (p.steps != null ? `${p.steps} steps` : null),
  ].filter(Boolean).join(' · ');

  return (
    <div
      className={'lib-card' + (hover ? ' is-hover' : '')}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      onClick={onOpen}
      style={{ opacity: deleting ? 0.4 : 1 }}
    >
      {/* Portrait image */}
      <div className="lib-portrait">
        {p.image ? (
          <img src={p.image} alt={p.name} className="lib-img" />
        ) : (
          <div className="lib-img lib-img-fallback" style={{
            background: `radial-gradient(ellipse at 50% 30%, ${(p.accent || 'var(--brand)')}33, transparent 62%), linear-gradient(180deg, var(--surface-2), var(--surface))`,
          }} />
        )}

        {/* Legibility scrim */}
        <div className="lib-scrim" />

        {/* Hover delete */}
        {onDelete && hover && (
          <button
            className="lib-del"
            title="Remove from library"
            disabled={deleting}
            onClick={(e) => { e.stopPropagation(); onDelete(); }}
          >×</button>
        )}

        {/* Overlay caption */}
        <div className="lib-caption">
          <div className="lib-name">{p.name}</div>
          {meta && <div className="lib-meta">{meta}</div>}
        </div>
      </div>

      {/* Palette ribbon + archetype */}
      <div className="lib-foot">
        <SwatchRibbon colours={(p.palette || []).slice(0, 5)} height={7} gap={2} />
        {p.archetype && <div className="lib-arch">{p.archetype}</div>}
      </div>
    </div>
  );
}

// ── Shimmer skeleton ───────────────────────────────────────────────
function SkeletonCard() {
  return (
    <div className="lib-card lib-skel">
      <div className="lib-portrait lib-shimmer" style={{ borderRadius: 'var(--r-lg)' }} />
      <div className="lib-foot">
        <div className="lib-shimmer" style={{ height: 7, borderRadius: 3 }} />
        <div className="lib-shimmer" style={{ height: 10, width: '60%', borderRadius: 4, marginTop: 10 }} />
      </div>
    </div>
  );
}

// ── Empty state ────────────────────────────────────────────────────
function EmptyLibrary({ navigate }) {
  return (
    <div style={{
      border: '1.5px dashed var(--line-2)',
      borderRadius: 'var(--r-lg)',
      padding: '72px 32px',
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16,
      textAlign: 'center',
    }}>
      <div style={{
        width: 58, height: 58, borderRadius: '50%',
        background: 'var(--surface)', border: '1px solid var(--line-2)',
        display: 'grid', placeItems: 'center', color: 'var(--brand)',
      }}><PMIcon name="library" size={26} /></div>
      <div>
        <div style={{ fontFamily: 'var(--serif)', fontSize: 27, fontWeight: 600 }}>No minis yet</div>
        <div style={{ fontSize: 13.5, color: 'var(--ink-3)', marginTop: 5, maxWidth: 320 }}>
          Finished designs land here as portraits — your painted trophy shelf.
        </div>
      </div>
      <button className="btn btn-gold" onClick={() => navigate('editor')}>
        Start your first design&nbsp; <span style={{ fontSize: 16 }}>+</span>
      </button>
    </div>
  );
}

// ── Injected styles (guarded against duplicates) ───────────────────
function injectLibraryStyles() {
  if (document.getElementById('library-styles')) return;
  const el = document.createElement('style');
  el.id = 'library-styles';
  el.textContent = `
    @keyframes libShimmer { 0% { background-position: -420px 0; } 100% { background-position: 420px 0; } }

    .lib-card { background: var(--surface); border: 1px solid var(--line);
      border-radius: var(--r-lg); overflow: hidden; cursor: pointer;
      transition: transform 200ms ease, box-shadow 200ms ease, border-color 200ms ease; }
    .lib-card.is-hover { transform: translateY(-5px);
      box-shadow: 0 20px 40px -24px rgba(40,30,20,0.28);
      border-color: var(--line-2); }

    .lib-portrait { position: relative; aspect-ratio: 3 / 4; overflow: hidden;
      border-top-left-radius: var(--r-lg); border-top-right-radius: var(--r-lg);
      background: var(--surface-2); }
    .lib-img { position: absolute; inset: 0; width: 100%; height: 100%;
      object-fit: cover; display: block;
      transition: transform 320ms ease; }
    .lib-card.is-hover .lib-img { transform: scale(1.04); }
    .lib-img-fallback { transition: none; }

    .lib-scrim { position: absolute; inset: 0; pointer-events: none;
      background: linear-gradient(180deg, rgba(28,26,23,0) 42%, rgba(28,26,23,0.14) 62%, rgba(28,26,23,0.72) 100%); }

    .lib-del { position: absolute; top: 10px; right: 10px; z-index: 3;
      width: 28px; height: 28px; border-radius: 50%;
      background: rgba(246,244,239,0.92); border: 1px solid var(--line-2);
      color: var(--brand-deep); font-size: 15px; font-weight: 600;
      display: grid; place-items: center; cursor: pointer;
      backdrop-filter: blur(6px); }
    .lib-del:hover { background: #fff; }

    .lib-caption { position: absolute; left: 0; right: 0; bottom: 0; z-index: 2;
      padding: 14px 15px 13px; color: var(--sidebar-ink); }
    .lib-name { font-family: var(--serif); font-weight: 600; font-size: 21px;
      line-height: 1.05; text-shadow: 0 1px 12px rgba(0,0,0,0.5); }
    .lib-meta { font-family: var(--mono); font-size: 9.5px; letter-spacing: 0.08em;
      text-transform: uppercase; margin-top: 5px; color: rgba(246,244,239,0.82);
      text-shadow: 0 1px 8px rgba(0,0,0,0.55); }

    .lib-foot { padding: 12px 14px 14px; }
    .lib-arch { font-size: 12px; color: var(--ink-3); margin-top: 9px;
      overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }

    .lib-skel { cursor: default; }
    .lib-shimmer { background: linear-gradient(90deg,
        var(--surface-2) 0%, var(--line) 40%, var(--surface-2) 80%);
      background-size: 840px 100%; animation: libShimmer 1.4s infinite linear; }
  `;
  document.head.appendChild(el);
}

Object.assign(window, { Library });
