/* Gallery — saved mosaics grid + detail view */

const GALLERY_STORAGE_KEY = 'penrose_gallery';

function galleryLoad() {
  try {
    const raw = localStorage.getItem(GALLERY_STORAGE_KEY);
    return raw ? JSON.parse(raw) : [];
  } catch { return []; }
}
function gallerySave(items) {
  localStorage.setItem(GALLERY_STORAGE_KEY, JSON.stringify(items));
}

function GalleryMiniCanvas({ tiles, revealed, palette, size = 120 }) {
  const canvasRef = React.useRef(null);
  React.useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas || !tiles) return;
    const ctx = canvas.getContext('2d');
    const w = canvas.width = size * 2;
    const h = canvas.height = size * 2;
    canvas.style.width = size + 'px';
    canvas.style.height = size + 'px';

    let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
    const revSet = new Set(revealed);
    for (const id of revealed) {
      const t = tiles[id];
      if (!t) continue;
      for (const v of t.verts) {
        minX = Math.min(minX, v.x); maxX = Math.max(maxX, v.x);
        minY = Math.min(minY, v.y); maxY = Math.max(maxY, v.y);
      }
    }
    const rangeX = maxX - minX || 1;
    const rangeY = maxY - minY || 1;
    const scale = Math.min((w - 20) / rangeX, (h - 20) / rangeY);
    const cx = w / 2, cy = h / 2;
    const midX = (minX + maxX) / 2, midY = (minY + maxY) / 2;

    ctx.clearRect(0, 0, w, h);
    for (const id of revealed) {
      const t = tiles[id];
      if (!t) continue;
      ctx.beginPath();
      t.verts.forEach((v, i) => {
        const px = cx + (v.x - midX) * scale;
        const py = cy - (v.y - midY) * scale;
        i === 0 ? ctx.moveTo(px, py) : ctx.lineTo(px, py);
      });
      ctx.closePath();
      ctx.fillStyle = t.type === 'thick' ? palette.thick : palette.thin;
      ctx.fill();
      ctx.strokeStyle = t.type === 'thick' ? palette.thickEdge : palette.thinEdge;
      ctx.lineWidth = 0.5;
      ctx.stroke();
    }
  }, [tiles, revealed, palette, size]);
  return <canvas ref={canvasRef} style={{ width: size, height: size, borderRadius: 12 }} />;
}

function GalleryDetail({ item, palette, onBack, onDelete }) {
  const tiles = React.useMemo(() => {
    if (!window.PenroseGeo) return [];
    return window.PenroseGeo.generateTiling({ radius: item.radius || 32, pattern: item.pattern });
  }, [item.pattern, item.radius]);

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 10,
      background: palette.bg1, color: palette.ink,
      display: 'flex', flexDirection: 'column',
      overflow: 'hidden',
    }}>
      {/* Header */}
      <div style={{
        padding: '52px 20px 14px', display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        borderBottom: `1px solid ${palette.dim}15`,
      }}>
        <div onClick={onBack} style={{
          width: 34, height: 34, borderRadius: 999,
          border: `1px solid ${palette.dim}22`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          cursor: 'pointer', WebkitTapHighlightColor: 'transparent',
        }}>
          <svg width="12" height="12" viewBox="0 0 14 14"><path d="M9 2L4 7l5 5" fill="none" stroke={palette.ink} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" /></svg>
        </div>
        <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 9, letterSpacing: '0.18em', color: palette.dim }}>
          #{item.patternId}
        </span>
        <div onClick={() => { if (confirm('Delete this mosaic?')) onDelete(item.id); }} style={{
          width: 34, height: 34, borderRadius: 999,
          border: `1px solid ${palette.dim}22`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          cursor: 'pointer', WebkitTapHighlightColor: 'transparent',
        }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
            <path d="M3 6h18M8 6V4a2 2 0 012-2h4a2 2 0 012 2v2m2 0v14a2 2 0 01-2 2H8a2 2 0 01-2-2V6h12z" stroke={palette.dim} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </div>
      </div>

      {/* Big preview */}
      <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16 }}>
        <GalleryMiniCanvas tiles={tiles} revealed={item.revealed} palette={palette} size={320} />
      </div>

      {/* Stats */}
      <div style={{
        padding: '16px 22px 32px',
        display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12,
      }}>
        {[
          { label: 'TILES', value: item.revealed.length },
          { label: 'SCORE', value: item.score },
          { label: 'MODE', value: (item.mode || 'zen').toUpperCase() },
        ].map(s => (
          <div key={s.label} style={{
            padding: '10px 8px', borderRadius: 12,
            background: `${palette.bg2}88`, border: `1px solid ${palette.dim}11`,
            textAlign: 'center',
          }}>
            <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 8, letterSpacing: '0.18em', color: palette.dim }}>{s.label}</div>
            <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 18, fontWeight: 700, marginTop: 3 }}>{s.value}</div>
          </div>
        ))}
        <div style={{ gridColumn: '1 / -1', textAlign: 'center' }}>
          <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, color: palette.dim }}>
            Seed: {item.patternId} · {item.date}
          </span>
        </div>
        <div style={{ gridColumn: '1 / -1', display: 'flex', gap: 10 }}>
          <button onClick={() => {
            if (navigator.share) {
              navigator.share({ title: 'Tessera Mosaic', text: `My Penrose mosaic #${item.patternId} — ${item.revealed.length} tiles, ${item.score} pts` });
            }
          }} style={{
            flex: 1, height: 42, borderRadius: 12, border: `1px solid ${palette.dim}33`,
            background: 'transparent', color: palette.ink,
            fontFamily: "'JetBrains Mono', monospace", fontSize: 10, fontWeight: 700,
            letterSpacing: '0.16em', cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
            WebkitTapHighlightColor: 'transparent',
          }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
              <path d="M4 12v8a2 2 0 002 2h12a2 2 0 002-2v-8M16 6l-4-4-4 4M12 2v13" stroke={palette.ink} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
            SHARE
          </button>
          <button onClick={() => {
            const canvas = document.querySelector('canvas');
            if (canvas) {
              const link = document.createElement('a');
              link.download = `tessera-${item.patternId}.png`;
              link.href = canvas.toDataURL('image/png');
              link.click();
            }
          }} style={{
            flex: 1, height: 42, borderRadius: 12, border: 'none',
            background: palette.thick, color: palette.bg1,
            fontFamily: "'JetBrains Mono', monospace", fontSize: 10, fontWeight: 700,
            letterSpacing: '0.16em', cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
            WebkitTapHighlightColor: 'transparent',
          }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
              <path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M7 10l5 5 5-5M12 15V3" stroke={palette.bg1} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
            EXPORT
          </button>
        </div>
      </div>
    </div>
  );
}

function GalleryScreen({ palette, isPro, onUpgrade }) {
  const [items, setItems] = React.useState(() => galleryLoad());
  const [detail, setDetail] = React.useState(null);

  function handleDelete(id) {
    const next = items.filter(i => i.id !== id);
    gallerySave(next);
    setItems(next);
    setDetail(null);
  }

  if (detail) {
    return <GalleryDetail item={detail} palette={palette} onBack={() => setDetail(null)} onDelete={handleDelete} />;
  }

  return (
    <div style={{
      flex: 1, display: 'flex', flexDirection: 'column',
      overflow: 'hidden', position: 'relative',
    }}>
      {/* Header */}
      <div style={{ padding: '52px 22px 14px', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end' }}>
        <div>
          <div style={{ fontSize: 24, fontWeight: 700, color: palette.ink }}>Gallery</div>
          <div style={{ fontSize: 12, color: palette.dim, marginTop: 3 }}>
            {items.length === 0 ? 'No saved mosaics yet' : `${items.length} mosaic${items.length > 1 ? 's' : ''}`}
          </div>
        </div>
      </div>

      {/* Grid or empty */}
      {items.length === 0 ? (
        <div style={{
          flex: 1, display: 'flex', flexDirection: 'column',
          alignItems: 'center', justifyContent: 'center', gap: 14,
          padding: '40px 28px', color: palette.dim,
        }}>
          <svg width="48" height="48" viewBox="0 0 24 24" fill="none" opacity="0.25">
            <rect x="3" y="3" width="7" height="7" rx="1.5" stroke={palette.dim} strokeWidth="1.5"/>
            <rect x="14" y="3" width="7" height="7" rx="1.5" stroke={palette.dim} strokeWidth="1.5"/>
            <rect x="3" y="14" width="7" height="7" rx="1.5" stroke={palette.dim} strokeWidth="1.5"/>
            <rect x="14" y="14" width="7" height="7" rx="1.5" stroke={palette.dim} strokeWidth="1.5"/>
          </svg>
          <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, letterSpacing: '0.2em' }}>NO MOSAICS YET</div>
          <div style={{ fontSize: 13, textAlign: 'center', lineHeight: 1.6, maxWidth: 240 }}>
            Complete a game and your mosaic will be saved here automatically.
          </div>
        </div>
      ) : (
        <div style={{
          flex: 1, overflowY: 'auto', padding: '4px 14px 20px',
          display: 'grid', gridTemplateColumns: '1fr 1fr',
          gap: 10, alignContent: 'start',
        }}>
          {items.map(item => {
            const tiles = window.PenroseGeo
              ? window.PenroseGeo.generateTiling({ radius: item.radius || 32, pattern: item.pattern })
              : [];
            return (
              <div key={item.id} onClick={() => setDetail(item)} style={{
                borderRadius: 16, overflow: 'hidden',
                background: `${palette.bg2}88`,
                border: `1px solid ${palette.dim}11`,
                cursor: 'pointer',
                WebkitTapHighlightColor: 'transparent',
              }}>
                <div style={{
                  width: '100%', aspectRatio: '1/1',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  background: palette.bg1,
                }}>
                  <GalleryMiniCanvas tiles={tiles} revealed={item.revealed} palette={palette} size={160} />
                </div>
                <div style={{ padding: '8px 10px 10px' }}>
                  <div style={{
                    fontFamily: "'JetBrains Mono', monospace", fontSize: 10, fontWeight: 700,
                    color: palette.ink, letterSpacing: '0.08em',
                  }}>#{item.patternId}</div>
                  <div style={{
                    fontFamily: "'JetBrains Mono', monospace", fontSize: 9,
                    color: palette.dim, marginTop: 2,
                  }}>{item.revealed.length} tiles · {item.score} pts</div>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

window.GalleryScreen = GalleryScreen;
window.gallerySave = gallerySave;
window.galleryLoad = galleryLoad;
