// src/detail.jsx — Detalhe da placa (3D, downloads, fotos, specs, observações)
const { useState: useSt, useEffect: useEf, useRef: useRf } = React;

function DetailScreen({ frame }) {
  const isMobile = frame === 'mobile';
  const [tab, setTab] = useSt('3d');
  const [copied, setCopied] = useSt('');
  const [downloaded, setDownloaded] = useSt({});

  const p = PLACA_DETAIL;

  const copy = (text, label) => {
    navigator.clipboard?.writeText(text);
    setCopied(label);
    setTimeout(() => setCopied(''), 1400);
  };

  const triggerDl = (id) => {
    setDownloaded(d => ({ ...d, [id]: 'pending' }));
    setTimeout(() => setDownloaded(d => ({ ...d, [id]: 'done' })), 900);
    setTimeout(() => setDownloaded(d => ({ ...d, [id]: undefined })), 2400);
  };

  return (
    <div style={{ paddingBottom: 80 }}>
      {/* HERO — preview + metadata */}
      <section style={{
        display: 'grid',
        gridTemplateColumns: isMobile ? '1fr' : '1.1fr 0.9fr',
        gap: isMobile ? 0 : 0,
        borderBottom: '1px solid var(--line-soft)',
      }}>
        {/* Preview pane */}
        <div style={{
          background: 'var(--bg-sunk)',
          borderRight: isMobile ? 'none' : '1px solid var(--line-soft)',
          padding: isMobile ? '28px 22px 36px' : '60px 60px 60px',
          minHeight: isMobile ? 360 : 560,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          position: 'relative',
        }}>
          {/* Tab pills */}
          <div style={{
            position: 'absolute', top: isMobile ? 18 : 28, left: isMobile ? 22 : 28,
            display: 'flex', gap: 4,
            padding: 4,
            background: 'var(--bg-elev)',
            border: '1px solid var(--line)',
            borderRadius: 999,
            zIndex: 10,
          }}>
            {[
              { id: '3d',     label: '3D',     icon: IconCube },
              { id: 'flat',   label: 'Arte',   icon: IconLayers },
              { id: 'photos', label: 'Fotos',  icon: IconCamera },
            ].map(t => (
              <button key={t.id} onClick={() => setTab(t.id)}
                style={{
                  display: 'inline-flex', alignItems: 'center', gap: 6,
                  padding: '6px 12px',
                  borderRadius: 999,
                  fontSize: 12,
                  fontWeight: 500,
                  color: tab === t.id ? 'var(--bg)' : 'var(--ink-soft)',
                  background: tab === t.id ? 'var(--ink)' : 'transparent',
                }}>
                <t.icon size={13}/> {t.label}
              </button>
            ))}
          </div>

          {/* Measurements badge */}
          <div style={{
            position: 'absolute', top: isMobile ? 18 : 28, right: isMobile ? 22 : 28,
            display: 'inline-flex', alignItems: 'center', gap: 6,
            padding: '6px 12px',
            background: 'var(--bg-elev)',
            border: '1px solid var(--line)',
            borderRadius: 999,
            fontFamily: 'var(--font-mono)',
            fontSize: 11,
            color: 'var(--ink-soft)',
            zIndex: 10,
          }}>
            <IconRuler size={12}/> {p.w} × {p.h} cm
          </div>

        <div style={{ width: '100%', maxWidth: isMobile ? 280 : 460, marginTop: isMobile ? 48 : 0 }}>
            {tab === '3d'     && <Viewer3D width={isMobile ? 240 : 420}/>}
            {tab === 'flat'   && <FlatView isMobile={isMobile}/>}
            {tab === 'photos' && <PhotosView/>}
          </div>
        </div>

        {/* Info pane */}
        <div style={{ padding: isMobile ? '32px 22px 28px' : '60px 56px' }}>
          <div className="eyebrow" style={{ marginBottom: 14 }}>
            {p.group} · {p.version}
          </div>
          <h1 className="display" style={{
            fontSize: isMobile ? 38 : 60, margin: 0, marginBottom: 16,
          }}>
            {p.name}
          </h1>

          {/* Code chips */}
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 24 }}>
            <CodeChip label="Código da placa" value={p.code} onCopy={() => copy(p.code, 'code')} copied={copied === 'code'} />
            <CodeChip label="Insumo Sienge" value={p.sienge} onCopy={() => copy(p.sienge, 'sienge')} copied={copied === 'sienge'} />
          </div>

          <p style={{
            color: 'var(--ink-soft)',
            lineHeight: 1.6,
            margin: '0 0 28px',
            fontSize: 14,
            maxWidth: 480,
          }}>
            {p.usage}
          </p>

          {/* Primary CTA */}
          <button onClick={() => triggerDl('all')}
            style={{
              width: '100%',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 10,
              padding: '16px 22px',
              background: 'var(--prestes-green)',
              color: '#0a2a0a',
              border: 'none',
              borderRadius: 'var(--radius)',
              fontWeight: 600,
              fontSize: 15,
              marginBottom: 12,
              boxShadow: '0 8px 24px -10px rgba(124, 215, 35, 0.6)',
            }}>
            {downloaded.all === 'pending' ? (<><Spinner/> Preparando pacote…</>)
              : downloaded.all === 'done' ? (<><IconCheck size={16}/> Baixado · 24.8 MB</>)
              : (<><IconDownload size={16}/> Baixar pacote completo · 24.8 MB</>)}
          </button>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            <button onClick={() => setTab('3d')}
              style={ghostBtn}>
              <IconCube size={14}/> Ver em 3D
            </button>
            <button onClick={() => setTab('photos')}
              style={ghostBtn}>
              <IconCamera size={14}/> Fotos instaladas
            </button>
          </div>

          {/* Inline meta */}
          <div style={{
            marginTop: 28,
            display: 'grid',
            gridTemplateColumns: '1fr 1fr',
            gap: '0 16px',
            rowGap: 14,
            paddingTop: 24,
            borderTop: '1px solid var(--line-soft)',
          }}>
            <MetaRow icon={IconRuler} label="Formato" value={`${p.w} × ${p.h} cm`} />
            <MetaRow icon={IconLayers} label="Material" value={p.material} />
            <MetaRow icon={IconPin} label="Fixação" value={p.fixation} />
            <MetaRow icon={IconCal} label="Inclusão" value={p.date} />
          </div>
        </div>
      </section>

      {/* DOWNLOADS section */}
      <section style={{ padding: isMobile ? '40px 22px 0' : '64px 80px 0' }}>
        <SectionHeader number="01" title="Arquivos para download" subtitle="Tudo o que o fornecedor precisa para produzir a peça com fidelidade." />
        <div style={{
          display: 'grid',
          gridTemplateColumns: isMobile ? '1fr' : 'repeat(3, 1fr)',
          gap: isMobile ? 8 : 12,
        }}>
          {p.downloads.map(d => (
            <DownloadCard key={d.id} dl={d} state={downloaded[d.id]} onClick={() => triggerDl(d.id)} />
          ))}
        </div>
      </section>

      {/* SPECS section */}
      <section style={{ padding: isMobile ? '52px 22px 0' : '88px 80px 0' }}>
        <SectionHeader number="02" title="Especificações" subtitle="Medidas, materiais e parâmetros oficiais. Não altere sem aprovação da Comunicação." />
        <div style={{
          background: 'var(--bg-elev)',
          border: '1px solid var(--line)',
          borderRadius: 'var(--radius-lg)',
          overflow: 'hidden',
        }}>
          {Object.entries(p.spec).map(([k, v], i) => (
            <div key={k} style={{
              display: 'grid',
              gridTemplateColumns: isMobile ? '120px 1fr' : '220px 1fr',
              padding: '16px 22px',
              borderTop: i === 0 ? 'none' : '1px solid var(--line-soft)',
              alignItems: 'center',
            }}>
              <div className="eyebrow">{k}</div>
              <div style={{ fontSize: 14, fontFamily: k === 'Código' || k === 'Insumo Sienge' || k === 'Cores' ? 'var(--font-mono)' : 'inherit' }}>
                {v}
              </div>
            </div>
          ))}
        </div>
      </section>

      {/* USAGE + OBS */}
      <section style={{ padding: isMobile ? '52px 22px 0' : '88px 80px 0' }}>
        <SectionHeader number="03" title="Indicação de uso" subtitle="" />
        <div style={{
          display: 'grid',
          gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr',
          gap: isMobile ? 12 : 18,
        }}>
          <InfoBlock title="Onde fixar" body={p.usage} accent="green"/>
          <InfoBlock title="Observações de uso" body={p.obs} accent="teal"/>
        </div>
      </section>

      {/* HISTORY mini */}
      <section style={{ padding: isMobile ? '52px 22px 0' : '88px 80px 0' }}>
        <SectionHeader number="04" title="Histórico" subtitle="Mudanças recentes desta peça." />
        <ol style={{
          listStyle: 'none',
          padding: 0, margin: 0,
          display: 'grid', gap: 0,
          background: 'var(--bg-elev)',
          border: '1px solid var(--line)',
          borderRadius: 'var(--radius-lg)',
          overflow: 'hidden',
        }}>
          {[
            { v: 'v2.1', d: '12.03.2026', who: 'Davi Prestes', note: 'Atualização da cor verde para Pantone 376C.' },
            { v: 'v2.0', d: '08.11.2025', who: 'Comunicação',  note: 'Reformulação completa do layout em 8 colunas.' },
            { v: 'v1.3', d: '22.06.2024', who: 'Marketing',    note: 'Inclusão do campo Alojamento.' },
          ].map((it, i) => (
            <li key={i} style={{
              display: 'grid',
              gridTemplateColumns: isMobile ? '60px 1fr' : '80px 110px 1fr 130px',
              padding: '16px 22px',
              borderTop: i === 0 ? 'none' : '1px solid var(--line-soft)',
              alignItems: 'center', gap: 14,
            }}>
              <div className="mono" style={{
                fontSize: 12, fontWeight: 600,
                color: i === 0 ? 'var(--prestes-teal)' : 'var(--ink-faint)',
              }}>{it.v}</div>
              {!isMobile && <div className="mono" style={{ fontSize: 11, color: 'var(--ink-faint)' }}>{it.d}</div>}
              <div style={{ fontSize: 13 }}>{it.note}</div>
              {!isMobile && <div className="mono" style={{ fontSize: 11, color: 'var(--ink-faint)', textAlign: 'right' }}>{it.who}</div>}
            </li>
          ))}
        </ol>
      </section>

      <div style={{ height: 80 }}/>
    </div>
  );
}

const ghostBtn = {
  display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
  padding: '12px 14px',
  background: 'var(--bg-elev)',
  border: '1px solid var(--line)',
  borderRadius: 'var(--radius)',
  color: 'var(--ink)',
  fontWeight: 500,
  fontSize: 13,
};

function SectionHeader({ number, title, subtitle }) {
  return (
    <div style={{
      display: 'flex',
      flexDirection: 'column',
      gap: 8,
      marginBottom: 24,
    }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 14 }}>
        <span className="mono" style={{
          fontSize: 11, color: 'var(--ink-faint)',
          letterSpacing: '0.12em',
        }}>{number}</span>
        <h2 className="display" style={{ fontSize: 32, margin: 0 }}>{title}</h2>
      </div>
      {subtitle && (
        <p style={{ margin: 0, color: 'var(--ink-soft)', fontSize: 14, maxWidth: 620 }}>{subtitle}</p>
      )}
    </div>
  );
}

function CodeChip({ label, value, onCopy, copied }) {
  return (
    <button onClick={onCopy} style={{
      display: 'inline-flex', alignItems: 'center', gap: 10,
      padding: '8px 12px 8px 14px',
      background: 'var(--bg-elev)',
      border: '1px solid var(--line)',
      borderRadius: 999,
    }}>
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start', lineHeight: 1 }}>
        <span className="eyebrow" style={{ fontSize: 9 }}>{label}</span>
        <span className="mono" style={{ fontSize: 13, fontWeight: 500, marginTop: 4 }}>{value}</span>
      </div>
      <span style={{
        width: 24, height: 24,
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        color: copied ? 'var(--prestes-teal)' : 'var(--ink-faint)',
        transition: 'color 0.2s',
      }}>
        {copied ? <IconCheck size={14}/> : <IconCopy size={13}/>}
      </span>
    </button>
  );
}

function MetaRow({ icon: Ic, label, value }) {
  return (
    <div>
      <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, color: 'var(--ink-faint)', marginBottom: 4 }}>
        <Ic size={12}/>
        <span className="eyebrow">{label}</span>
      </div>
      <div style={{ fontSize: 13.5, fontWeight: 500 }}>{value}</div>
    </div>
  );
}

function InfoBlock({ title, body, accent }) {
  const accentColor = accent === 'green' ? 'var(--prestes-green)' : 'var(--prestes-teal)';
  return (
    <div style={{
      background: 'var(--bg-elev)',
      border: '1px solid var(--line)',
      borderRadius: 'var(--radius-lg)',
      padding: 24,
      position: 'relative',
      overflow: 'hidden',
    }}>
      <div style={{
        position: 'absolute', top: 0, left: 0, bottom: 0,
        width: 4, background: accentColor,
      }}/>
      <h3 style={{ margin: '0 0 10px', fontSize: 15, fontWeight: 600 }}>{title}</h3>
      <p style={{ margin: 0, color: 'var(--ink-soft)', fontSize: 14, lineHeight: 1.6 }}>{body}</p>
    </div>
  );
}

function DownloadCard({ dl, state, onClick }) {
  const typeColor = {
    curva: 'var(--prestes-teal)',
    edit: '#8B5CF6',
    imagem: '#0EA5E9',
    fonte: '#F59E0B',
    extra: 'var(--ink-soft)',
    all: 'var(--prestes-green-deep)',
  }[dl.type] || 'var(--ink-soft)';

  return (
    <button onClick={onClick}
      style={{
        textAlign: 'left',
        background: dl.type === 'all' ? 'color-mix(in oklch, var(--prestes-green) 12%, var(--bg-elev))' : 'var(--bg-elev)',
        border: '1px solid ' + (dl.type === 'all' ? 'color-mix(in oklch, var(--prestes-green) 40%, var(--line))' : 'var(--line)'),
        borderRadius: 'var(--radius)',
        padding: 18,
        display: 'flex', alignItems: 'center', gap: 14,
        transition: 'all 0.15s',
      }}
      onMouseEnter={e => e.currentTarget.style.borderColor = 'var(--ink-soft)'}
      onMouseLeave={e => e.currentTarget.style.borderColor = dl.type === 'all' ? 'color-mix(in oklch, var(--prestes-green) 40%, var(--line))' : 'var(--line)'}
    >
      <div style={{
        width: 44, height: 44,
        borderRadius: 10,
        background: 'var(--bg-sunk)',
        border: '1px solid var(--line)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0,
        position: 'relative',
      }}>
        <span className="mono" style={{ fontSize: 10, fontWeight: 600, color: typeColor }}>{dl.ext}</span>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13.5, fontWeight: 500, marginBottom: 2 }}>{dl.label}</div>
        <div className="mono" style={{ fontSize: 10.5, color: 'var(--ink-faint)' }}>
          {dl.size} · {dl.type}
        </div>
      </div>
      <div style={{
        width: 32, height: 32,
        borderRadius: 999,
        background: 'transparent',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: state === 'done' ? 'var(--prestes-teal)' : 'var(--ink-soft)',
        flexShrink: 0,
      }}>
        {state === 'pending' ? <Spinner/>
          : state === 'done' ? <IconCheck size={16}/>
          : <IconDownload size={16}/>}
      </div>
    </button>
  );
}

function FlatView({ isMobile }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14 }}>
      <PlacaArt size={isMobile ? 260 : 460}/>
      <div className="mono" style={{ fontSize: 11, color: 'var(--ink-faint)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>
        Arte vetorial · escala 1:1
      </div>
    </div>
  );
}

function PhotosView() {
  const [active, setActive] = useSt(0);
  const photos = PLACA_DETAIL.photos;
  const tones = {
    a: 'linear-gradient(135deg, #4a5d4f, #2a3530)',
    b: 'linear-gradient(135deg, #6b6b6b, #3a3a3a)',
    c: 'linear-gradient(135deg, #c4b896, #8b7d5b)',
    d: 'linear-gradient(135deg, #5a6a78, #2a3a48)',
  };
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12, width: '100%' }}>
      <div style={{
        aspectRatio: '4/3',
        background: tones[photos[active].tone],
        borderRadius: 'var(--radius)',
        position: 'relative',
        overflow: 'hidden',
        display: 'flex', alignItems: 'flex-end',
        padding: 18,
      }}>
        {/* synthetic photo composition — gradient + abstract framing, no fake content */}
        <div style={{
          position: 'absolute',
          top: '20%', left: '15%',
          width: '50%', aspectRatio: '160/140',
          background: 'rgba(255,255,255,0.92)',
          boxShadow: '0 20px 40px rgba(0,0,0,0.4)',
          transform: 'rotate(-2deg) perspective(800px) rotateY(-8deg)',
        }}>
          <div style={{ position: 'absolute', top: '20%', left: '6%', right: '6%', height: '8%', background: 'var(--prestes-green)' }}/>
          <div style={{ position: 'absolute', top: '30%', left: '6%', right: '6%', bottom: '8%', background: 'repeating-linear-gradient(0deg, #e8e8e8 0 6%, transparent 6% 8%)' }}/>
        </div>
        <div style={{
          position: 'relative', zIndex: 2,
          background: 'rgba(0,0,0,0.5)',
          backdropFilter: 'blur(10px)',
          padding: '8px 12px',
          borderRadius: 8,
          color: '#fff',
          fontFamily: 'var(--font-mono)',
          fontSize: 11,
          textTransform: 'uppercase',
          letterSpacing: '0.08em',
        }}>
          {photos[active].label}
        </div>
      </div>

      <div style={{ display: 'flex', gap: 6, justifyContent: 'center' }}>
        {photos.map((ph, i) => (
          <button key={ph.id} onClick={() => setActive(i)}
            style={{
              width: 44, height: 36,
              borderRadius: 6,
              background: tones[ph.tone],
              border: active === i ? '2px solid var(--prestes-green)' : '2px solid transparent',
              opacity: active === i ? 1 : 0.6,
              padding: 0,
            }}/>
        ))}
      </div>
    </div>
  );
}

function Spinner() {
  return (
    <svg width="16" height="16" viewBox="0 0 24 24">
      <circle cx="12" cy="12" r="9" stroke="currentColor" strokeWidth="2.5" fill="none" opacity="0.2"/>
      <path d="M21 12a9 9 0 0 0-9-9" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" fill="none">
        <animateTransform attributeName="transform" type="rotate" from="0 12 12" to="360 12 12" dur="0.9s" repeatCount="indefinite"/>
      </path>
    </svg>
  );
}

window.DetailScreen = DetailScreen;
