// ── Public report — read-only shareable design page (no auth) ────────
// Renders /share/:id from /api/public/projects/:id. Anyone with the link
// can view the painted plate, palette, and full step-by-step guide.

function pubPaintFor(value) {
  if (!value || typeof value !== 'string') return null;
  const v = value.trim().toLowerCase();
  return PAINTS.find(p => p.hex.toLowerCase() === v)
      || PAINTS.find(p => p.name.toLowerCase() === v)
      || PAINTS.find(p => p.name.toLowerCase().includes(v) || v.includes(p.name.toLowerCase()))
      || null;
}
const pubIsHex = (c) => /^#?[0-9a-fA-F]{6}$/.test(String(c || '').trim());
const pubIsTech = (t) => {
  const s = String(t || '').trim().toLowerCase();
  return s && s !== 'null' && s !== 'none' && s !== 'n/a';
};

function PublicReport({ navigate, projectId, isAuthed }) {
  const [project, setProject] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [showOriginal, setShowOriginal] = useState(false);

  useEffect(() => {
    let cancelled = false;
    setLoading(true);
    Api.publicProject(projectId)
      .then(p => { if (!cancelled) setProject(p); })
      .catch(err => { if (!cancelled) setError(err.message || 'Not found'); })
      .finally(() => { if (!cancelled) setLoading(false); });
    return () => { cancelled = true; };
  }, [projectId]);

  const variant = project?.advanced_scheme ? 'advanced' : 'beginner';
  const scheme = project ? (variant === 'advanced' ? project.advanced_scheme : project.beginner_scheme) || {} : {};
  const steps = project ? (variant === 'advanced' ? project.steps_advanced : project.steps_beginner) || [] : [];
  const painted = project ? (project.generated_advanced_image || project.generated_beginner_image) : null;
  const title = scheme.theme || 'Painted miniature';
  const desc = scheme.description || scheme.color_placement || '';
  const timeStr = scheme.estimated_time || '—';
  const colors = scheme.colors || [];
  const techniques = [...new Set((steps || []).map(s => s.technique).filter(pubIsTech))];
  const baseImage = project ? project.miniature_image : null;
  const diffLabel = scheme.difficulty || (variant === 'advanced' ? 'Advanced' : 'Beginner');
  const canCompare = !!painted && !!baseImage;
  const shownSrc = showOriginal && baseImage ? baseImage : painted;

  const goCreate = () => navigate(isAuthed ? 'studio' : 'auth', isAuthed ? {} : { mode: 'signup' });

  return (
    <div data-screen-label="share" style={{ background: 'var(--bg)', minHeight: '100vh' }}>
      {/* Public header */}
      <div style={{ background: 'var(--sidebar)', color: 'var(--sidebar-ink)' }}>
        <div style={{ maxWidth: 1000, margin: '0 auto', display: 'flex', alignItems: 'center', gap: 14, height: 60, padding: '0 24px' }}>
          <img className="pm-logo pm-logo--dark" src="/assets/logo-new.png" alt="PaintMini" />
          <span className="mono" style={{ fontSize: 10, letterSpacing: '0.12em', color: 'var(--sidebar-ink-3)' }}>SHARED GUIDE</span>
          <div style={{ flex: 1 }} />
          <button className="btn btn-gold btn-sm" onClick={goCreate}>Paint your own ↦</button>
        </div>
      </div>

      {loading ? (
        <div style={{ padding: '120px 24px', textAlign: 'center', color: 'var(--ink-3)' }}>
          <span style={{ display: 'inline-block', width: 30, height: 30, borderRadius: '50%', border: '3px solid var(--line-2)', borderTopColor: 'var(--brand)', animation: 'pm-spin 0.8s linear infinite' }} />
          <div className="mono" style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', marginTop: 14 }}>Loading guide…</div>
          <style>{`@keyframes pm-spin { to { transform: rotate(360deg); } }`}</style>
        </div>
      ) : error || !project ? (
        <div style={{ padding: '120px 24px', textAlign: 'center' }}>
          <h1 className="display" style={{ fontSize: 40, marginBottom: 12 }}><em>Guide not found</em></h1>
          <div style={{ color: 'var(--ink-3)', marginBottom: 24 }}>This shared link may be invalid or the design was removed.</div>
          <button className="btn btn-gold" onClick={goCreate}>Create your own ↦</button>
        </div>
      ) : (
        <div style={{ maxWidth: 1000, margin: '0 auto', padding: '32px 24px 64px' }}>
          {/* Title */}
          <span className="eyebrow" style={{ color: 'var(--brand-deep)' }}>{scheme.difficulty || (variant === 'advanced' ? 'Advanced' : 'Beginner')} guide</span>
          <h1 className="display" style={{ fontSize: 'clamp(36px, 5vw, 56px)', lineHeight: 1, margin: '8px 0 10px' }}><em>{title}</em></h1>
          {desc && <p style={{ color: 'var(--ink-2)', fontSize: 15, maxWidth: 620, lineHeight: 1.55, margin: '0 0 18px' }}>{desc}</p>}
          <div style={{ display: 'flex', gap: 26, marginBottom: 28 }}>
            {[['Time', timeStr], ['Steps', steps.length || '—'], ['Paints', colors.length || '—']].map(([k, v]) => (
              <div key={k}>
                <div style={{ fontFamily: 'var(--serif)', fontSize: 26, fontWeight: 600, lineHeight: 1 }}>{v}</div>
                <div className="mono" style={{ fontSize: 9, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--ink-3)', marginTop: 3 }}>{k}</div>
              </div>
            ))}
          </div>

          <div className="pm-split" style={{ ['--split']: '0.85fr 1.15fr', gap: 24, alignItems: 'start' }}>
            {/* Left: image + palette */}
            <div className="pm-sticky-col" style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
                <div style={{ position: 'relative', aspectRatio: '3 / 4', background: 'var(--surface-2)' }}>
                  {painted ? (
                    <img key={showOriginal ? 'orig' : 'painted'} src={shownSrc} alt={title} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
                  ) : (
                    <div style={{ height: '100%', display: 'grid', placeItems: 'center', color: 'var(--ink-3)', fontSize: 13 }}>Plate not rendered</div>
                  )}
                  {painted && (
                    <>
                      <span className="mono" style={{ position: 'absolute', top: 12, left: 14, fontSize: 9, letterSpacing: '0.1em', color: '#fff', textShadow: '0 1px 3px rgba(0,0,0,0.6)' }}>
                        {showOriginal ? 'YOUR PHOTO · UNPAINTED' : `SCHEME ${variant === 'beginner' ? 'A' : 'B'} · ${diffLabel.toUpperCase()}`}
                      </span>
                      {!showOriginal && (
                        <span className="mono" style={{ position: 'absolute', top: 10, right: 12, padding: '4px 10px', borderRadius: 4, background: 'var(--brand)', color: '#242424', fontSize: 9, fontWeight: 600, letterSpacing: '0.06em' }}>{diffLabel.toUpperCase()}</span>
                      )}
                      {canCompare && (
                        <div style={{ position: 'absolute', bottom: 12, left: '50%', transform: 'translateX(-50%)', display: 'flex', background: 'rgba(28,26,23,0.72)', backdropFilter: 'blur(6px)', borderRadius: 100, padding: 3, gap: 2 }}>
                          {[['painted', 'Painted'], ['original', 'Original']].map(([key, label]) => {
                            const on = (key === 'original') === showOriginal;
                            return (
                              <button key={key} onClick={() => setShowOriginal(key === 'original')} style={{ padding: '6px 14px', borderRadius: 100, fontSize: 11, fontWeight: 600, background: on ? 'var(--brand)' : 'transparent', color: on ? '#242424' : 'rgba(246,244,239,0.85)' }}>{label}</button>
                            );
                          })}
                        </div>
                      )}
                    </>
                  )}
                </div>
              </div>
              <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
                <div style={{ borderBottom: '2px solid var(--ink)', padding: '11px 16px', display: 'flex', justifyContent: 'space-between' }}>
                  <span style={{ fontSize: 12, fontWeight: 800, letterSpacing: '0.05em', textTransform: 'uppercase' }}>Palette</span>
                  <span className="mono" style={{ fontSize: 9, color: 'var(--ink-3)' }}>{colors.length} PAINTS</span>
                </div>
                {colors.map((hex, i) => {
                  const paint = pubPaintFor(hex);
                  return (
                    <div key={i} style={{ display: 'grid', gridTemplateColumns: '24px 1fr auto', gap: 12, alignItems: 'center', padding: '9px 16px', borderBottom: i === colors.length - 1 ? 'none' : '1px solid var(--line)' }}>
                      <span style={{ width: 24, height: 24, borderRadius: 5, background: pubIsHex(hex) ? hex : (paint?.hex || 'var(--surface-3)'), boxShadow: 'inset 0 0 0 1px rgba(0,0,0,0.2)' }} />
                      <span style={{ fontSize: 12.5, fontWeight: 500 }}>{paint?.name || `Colour ${i + 1}`}</span>
                      <span className="mono" style={{ fontSize: 9.5, color: 'var(--ink-3)' }}>{paint ? `${paint.brand.toUpperCase()} · ${paint.code}` : ''}</span>
                    </div>
                  );
                })}
              </div>
              {techniques.length > 0 && (
                <div className="card" style={{ padding: '13px 16px' }}>
                  <div style={{ fontSize: 12, fontWeight: 800, letterSpacing: '0.05em', textTransform: 'uppercase', marginBottom: 10 }}>Techniques</div>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                    {techniques.map(t => (
                      <span key={t} style={{ padding: '4px 11px', borderRadius: 4, background: 'var(--surface-2)', border: '1px solid var(--line)', fontSize: 11, color: 'var(--ink-2)' }}>{t}</span>
                    ))}
                  </div>
                </div>
              )}
            </div>

            {/* Right: steps */}
            <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
              <div style={{ borderBottom: '2px solid var(--ink)', padding: '14px 20px', display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ fontSize: 13, fontWeight: 800, letterSpacing: '0.05em', textTransform: 'uppercase' }}>Step by Step</span>
                <span className="mono" style={{ fontSize: 10, color: 'var(--ink-3)' }}>{steps.length} STEPS · {timeStr}</span>
              </div>
              {steps.map((s, i) => (
                <div key={i} style={{ display: 'grid', gridTemplateColumns: '28px 1fr', gap: 14, padding: '16px 22px', borderBottom: i === steps.length - 1 ? 'none' : '1px solid var(--line)' }}>
                  <span style={{ width: 28, height: 28, borderRadius: '50%', background: 'var(--sidebar)', color: '#fff', fontFamily: 'var(--mono)', fontSize: 11, fontWeight: 600, display: 'grid', placeItems: 'center', alignSelf: 'flex-start' }}>{s.step || i + 1}</span>
                  <div>
                    <div style={{ fontSize: 14, lineHeight: 1.5 }}>{s.action}</div>
                    {s.tip && <div style={{ fontSize: 12.5, color: 'var(--ink-3)', fontStyle: 'italic', margin: '8px 0 0', paddingLeft: 10, borderLeft: '2px solid var(--line-2)' }}>{s.tip}</div>}
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, alignItems: 'center', marginTop: 8 }}>
                      {pubIsTech(s.technique) && (
                        <span className="mono" style={{ padding: '3px 9px', borderRadius: 4, background: 'var(--brand-soft)', color: '#B3611F', fontSize: 9, fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase' }}>{s.technique}</span>
                      )}
                      {(s.colors || []).filter(c => c && String(c).toLowerCase() !== 'null').map((c, j) => {
                        const paint = pubPaintFor(c);
                        const swatch = paint?.hex || (pubIsHex(c) ? (String(c)[0] === '#' ? c : '#' + c) : null);
                        return (
                          <span key={j} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '3px 10px 3px 4px', borderRadius: 100, background: 'var(--surface-2)', border: '1px solid var(--line)', fontSize: 11, color: 'var(--ink-2)' }}>
                            <span style={{ width: 12, height: 12, borderRadius: 3, background: swatch || 'var(--surface-3)', boxShadow: 'inset 0 0 0 1px rgba(0,0,0,0.2)' }} />
                            {paint?.name || (pubIsHex(c) ? 'Colour' : c)}
                          </span>
                        );
                      })}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* CTA footer */}
          <div style={{ marginTop: 34, padding: '28px 26px', borderRadius: 16, background: 'var(--sidebar)', color: 'var(--sidebar-ink)', display: 'flex', alignItems: 'center', gap: 20, flexWrap: 'wrap' }}>
            <div style={{ flex: 1, minWidth: 240 }}>
              <div className="display" style={{ fontSize: 26, color: 'var(--sidebar-ink)' }}>Turn your photo into a <em>painted plate</em>.</div>
              <div style={{ color: 'var(--sidebar-ink-2)', fontSize: 13.5, marginTop: 6 }}>Upload an unpainted mini, pick your paints, and get a full step-by-step guide.</div>
            </div>
            <button className="btn btn-gold" style={{ height: 50 }} onClick={goCreate}>Paint your own ↦</button>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { PublicReport });
