// b/deck.jsx — swipeable project deck.

function Deck({ projects, onOpen, onSave, motion, savedIds, topBar, brickCount }) {
  const [idx, setIdx] = React.useState(0);
  const [drag, setDrag] = React.useState({ dx: 0, dy: 0, active: false });
  const [leaving, setLeaving] = React.useState(null); // {dir}
  const start = React.useRef(null);

  const cur = projects[idx];
  const next1 = projects[idx + 1];
  const next2 = projects[idx + 2];

  const commit = (dir) => {
    if (dir === 'right') { onOpen(cur); return; }
    const fly = dir === 'left' ? -1 : 0;
    const flyUp = dir === 'up' ? -1 : 0;
    setLeaving({ dir });
    if (dir === 'up') onSave(cur);
    setTimeout(() => {
      setLeaving(null);
      setDrag({ dx: 0, dy: 0, active: false });
      setIdx(i => Math.min(i + 1, projects.length));
    }, motion ? 280 : 0);
  };

  const onDown = (e) => {
    if (leaving) return;
    start.current = { x: e.clientX, y: e.clientY };
    setDrag(d => ({ ...d, active: true }));
    e.currentTarget.setPointerCapture(e.pointerId);
  };
  const onMove = (e) => {
    if (!start.current) return;
    setDrag({ dx: e.clientX - start.current.x, dy: e.clientY - start.current.y, active: true });
  };
  const onUp = () => {
    if (!start.current) return;
    const { dx, dy } = drag;
    start.current = null;
    if (dy < -110 && Math.abs(dy) > Math.abs(dx)) return commit('up');
    if (dx > 105) return commit('right');
    if (dx < -105) return commit('left');
    setDrag({ dx: 0, dy: 0, active: false });
  };

  if (!cur) {
    return (
      <div style={{ position: 'absolute', inset: 0, background: T.paper, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 14, padding: 30, textAlign: 'center' }}>
        <div style={{ fontFamily: disp, fontSize: 22, fontWeight: 700, color: T.ink }}>Det var alle forslag</div>
        <div style={{ fontFamily: disp, fontSize: 14, color: T.ink2, lineHeight: 1.5 }}>Du har set alle {projects.length} modeller der matcher dit inventar. Scan flere klodser for nye forslag.</div>
        <Btn kind="ghost" onClick={() => setIdx(0)} style={{ width: 'auto', marginTop: 6 }}>Se dem igen</Btn>
      </div>
    );
  }

  const flyX = leaving ? (leaving.dir === 'left' ? -500 : leaving.dir === 'up' ? drag.dx : 0) : drag.dx;
  const flyY = leaving ? (leaving.dir === 'up' ? -700 : 0) : drag.dy;
  const rot = (flyX) / 22;
  const overlay = drag.dx > 40 ? 'byg' : drag.dx < -40 ? 'vrag' : drag.dy < -40 ? 'gem' : null;

  return (
    <div style={{ position: 'absolute', inset: 0, background: T.paper, display: 'flex', flexDirection: 'column' }}>
      {topBar}
      {/* header */}
      <div style={{ padding: '12px 18px 6px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div>
          <div style={{ fontFamily: mono, fontSize: 10, color: T.ink2, letterSpacing: 0.5 }}>FORSLAG · MATCHER {brickCount} KLODSER</div>
          <div style={{ fontFamily: disp, fontSize: 19, fontWeight: 700, color: T.ink }}>Hvad vil du bygge?</div>
        </div>
        <div style={{ fontFamily: mono, fontSize: 12, color: T.ink2 }}>{idx + 1}/{projects.length}</div>
      </div>

      {/* stack */}
      <div style={{ position: 'relative', flex: 1, margin: '6px 18px 0' }}>
        {next2 && <CardShell key={next2.id} style={{ transform: 'translateY(20px) scale(.92)', opacity: .5 }} project={next2} dim />}
        {next1 && <CardShell key={next1.id} style={{ transform: 'translateY(10px) scale(.96)', opacity: .8 }} project={next1} dim />}
        <CardShell
          key={cur.id}
          project={cur}
          saved={savedIds.includes(cur.id)}
          onPointerDown={onDown} onPointerMove={onMove} onPointerUp={onUp} onPointerCancel={onUp}
          overlay={overlay}
          onClick={() => { if (Math.abs(drag.dx) < 6 && Math.abs(drag.dy) < 6) onOpen(cur); }}
          style={{
            transform: `translate(${flyX}px, ${flyY}px) rotate(${rot}deg)`,
            transition: drag.active && !leaving ? 'none' : 'transform .28s cubic-bezier(.2,.7,.3,1)',
            cursor: 'grab', touchAction: 'none',
          }}
        />
      </div>

      {/* actions */}
      <div style={{ display: 'flex', gap: 16, justifyContent: 'center', alignItems: 'center', padding: '14px 0 20px' }}>
        <ActionBtn label="vrag" onClick={() => commit('left')}>✕</ActionBtn>
        <ActionBtn label="gem" big onClick={() => commit('up')} accentRing>♥</ActionBtn>
        <ActionBtn label="byg" onClick={() => commit('right')} solid>→</ActionBtn>
      </div>
    </div>
  );
}

function CardShell({ project, style, dim, overlay, saved, ...handlers }) {
  return (
    <div {...handlers} style={{
      position: 'absolute', inset: 0, background: T.paper2, borderRadius: 20,
      border: '1px solid ' + T.line, overflow: 'hidden',
      boxShadow: dim ? 'none' : '0 18px 40px rgba(28,27,22,.16)',
      display: 'flex', flexDirection: 'column', userSelect: 'none', ...style,
    }}>
      {/* art */}
      <div style={{ position: 'relative', flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center',
        background: 'radial-gradient(120% 90% at 50% 30%, #fff 0%, ' + T.paper2 + ' 70%)' }}>
        <div style={{ position: 'absolute', inset: 0, opacity: .5,
          backgroundImage: 'radial-gradient(' + T.line + ' 1px, transparent 1px)', backgroundSize: '14px 14px' }} />
        <SetArt project={project} size={210} />
        {!dim && (
          <div style={{ position: 'absolute', top: 12, right: 12 }}>
            <Chip accent={project.match >= 70} solid={project.match >= 70}>{project.match}% match</Chip>
          </div>
        )}
        {!dim && saved && (
          <div style={{ position: 'absolute', top: 12, left: 12, fontFamily: mono, fontSize: 10, color: 'var(--accent)' }}>♥ gemt</div>
        )}
        {overlay && (
          <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
            background: overlay === 'vrag' ? 'rgba(28,27,22,.14)' : 'color-mix(in oklab, var(--accent) 16%, transparent)' }}>
            <span style={{
              fontFamily: disp, fontWeight: 700, fontSize: 30, letterSpacing: 2, textTransform: 'uppercase',
              color: overlay === 'vrag' ? T.ink : 'var(--accent)',
              border: '3px solid ' + (overlay === 'vrag' ? T.ink : 'var(--accent)'),
              padding: '4px 16px', borderRadius: 10, transform: 'rotate(-8deg)',
            }}>{overlay}</span>
          </div>
        )}
      </div>
      {/* info */}
      {!dim && (
        <div style={{ padding: '14px 16px 16px', background: T.paper }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <div style={{ fontFamily: disp, fontSize: 22, fontWeight: 700, color: T.ink }}>{project.name}</div>
            <span style={{ fontFamily: mono, fontSize: 10, color: T.ink2 }}>{project.cat}</span>
          </div>
          <div style={{ display: 'flex', gap: 7, marginTop: 10, alignItems: 'center', flexWrap: 'wrap' }}>
            <Chip><Diff level={project.diff} /></Chip>
            <Chip>{project.year || '—'}</Chip>
            <Chip>{project.parts} dele</Chip>
          </div>
          <div style={{ marginTop: 10, fontFamily: mono, fontSize: 11, color: project.missTotal ? 'var(--accent)' : T.ink2 }}>
            {project.missTotal ? `mangler ${project.missTotal} klodser` : '✓ du har alle delene'}
          </div>
        </div>
      )}
    </div>
  );
}

function ActionBtn({ children, label, onClick, big, solid, accentRing }) {
  const s = big ? 62 : 52;
  return (
    <button onClick={onClick} style={{ background: 'none', border: 'none', cursor: 'pointer', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
      <span style={{
        width: s, height: s, borderRadius: s, display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: big ? 24 : 20,
        background: solid ? 'var(--accent)' : T.paper,
        color: solid ? '#fff' : (accentRing ? 'var(--accent)' : T.ink),
        border: '1.5px solid ' + (solid ? 'var(--accent)' : (accentRing ? 'var(--accent)' : T.line)),
        boxShadow: '0 6px 16px rgba(28,27,22,.12)',
        transition: 'transform .1s',
      }}
      onMouseDown={e => e.currentTarget.style.transform = 'scale(.9)'}
      onMouseUp={e => e.currentTarget.style.transform = ''}
      onMouseLeave={e => e.currentTarget.style.transform = ''}
      >{children}</span>
      <span style={{ fontFamily: mono, fontSize: 9, color: T.ink2, letterSpacing: 1, textTransform: 'uppercase' }}>{label}</span>
    </button>
  );
}

Object.assign(window, { Deck });
