// ADOS website — shared pieces
const { Card, Tag, Badge } = window.ADOSDesignSystem_5aafbb;

function ProjectCard({ p, onOpen }) {
  return (
    <div onClick={() => onOpen && onOpen(p)} style={{ cursor: onOpen ? 'pointer' : 'default' }}>
      <Card media={p.img} mediaHeight={196} interactive={!!onOpen} padding={20}>
        <div style={{ display: 'flex', gap: 8, marginBottom: 12 }}>
          <Tag tone="amber">{p.discipline}</Tag>
          <Tag tone="outline">{p.lod}</Tag>
        </div>
        <h3 style={{ fontSize: 19, lineHeight: 1.15, margin: '0 0 8px' }}>{p.title}</h3>
        <p style={{ margin: 0, color: 'var(--text-muted)', fontSize: 13.5, lineHeight: 1.55 }}>{p.summary}</p>
        {p.result && (
          <div style={{ marginTop: 14, display: 'flex', alignItems: 'baseline', gap: 8 }}>
            <span style={{ width: 14, height: 2, background: 'var(--accent)', transform: 'skewX(-24deg)', flex: 'none', alignSelf: 'center' }} />
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: '0.68rem', letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--accent)' }}>{p.result}</span>
          </div>
        )}
        <div style={{ marginTop: 16, paddingTop: 14, borderTop: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', fontSize: 12, color: 'var(--text-faint)', letterSpacing: '0.04em' }}>
          <span>{p.location}</span><span>{p.year}</span>
        </div>
      </Card>
    </div>
  );
}

function SectionLabel({ children, n }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 18 }}>
      {n && <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, color: 'var(--accent)', fontSize: 13 }}>{n}</span>}
      <span style={{ fontSize: '0.7rem', textTransform: 'uppercase', letterSpacing: '0.1em', color: 'var(--text-muted)' }}>{children}</span>
      <span style={{ flex: 1, height: 1, background: 'var(--border)' }} />
    </div>
  );
}

window.ProjectCard = ProjectCard;
window.SectionLabel = SectionLabel;

// ===== VISOR ROTATORIO — secuencia de vistas isométricas controlada con un
// slider (y arrastre sobre la imagen). Los frames se precargan para que el
// giro sea fluido. =====
function ProjectTurntable({ frames, title }) {
  const [idx, setIdx] = React.useState(0);
  const [zoom, setZoom] = React.useState(1); // 1× a 2.5×, slider vertical derecho
  const boxRef = React.useRef(null);
  const drag = React.useRef(null); // { startX, startIdx }

  // Precarga de todos los frames al montar
  React.useEffect(() => {
    frames.forEach((src) => { const im = new Image(); im.src = src; });
  }, [frames]);

  const n = frames.length;
  const mod = (v) => ((v % n) + n) % n;
  // El slider tiene una posición extra al final (n) que repite el primer frame:
  // la vuelta inicia y termina en la misma imagen (360° completos).
  const view = mod(idx);

  // Arrastre horizontal sobre la imagen: una vuelta completa ≈ el ancho del visor
  const onDown = (e) => {
    drag.current = { startX: e.clientX, startIdx: idx };
    e.currentTarget.setPointerCapture && e.currentTarget.setPointerCapture(e.pointerId);
  };
  const onMove = (e) => {
    if (!drag.current) return;
    const box = boxRef.current;
    const w = box ? box.getBoundingClientRect().width : 800;
    const delta = Math.round(((e.clientX - drag.current.startX) / w) * n);
    setIdx(mod(drag.current.startIdx + delta));
  };
  const onUp = () => { drag.current = null; };

  return (
    <div>
      <div
        ref={boxRef}
        className="w-turntable"
        onPointerDown={onDown} onPointerMove={onMove} onPointerUp={onUp} onPointerCancel={onUp}
        role="slider" aria-label={`Rotar vista de ${title}`} aria-valuemin={0} aria-valuemax={n} aria-valuenow={idx}
        tabIndex={0}
        onKeyDown={(e) => {
          if (e.key === 'ArrowLeft') setIdx((v) => mod(v - 1));
          if (e.key === 'ArrowRight') setIdx((v) => mod(v + 1));
        }}
      >
        {/* Todos los frames apilados; solo el activo es visible (evita parpadeo al cambiar) */}
        {frames.map((src, i) => (
          <img key={src} src={src} alt={i === view ? `${title} — vista ${i + 1} de ${n}` : ''} aria-hidden={i !== view}
            style={{ width: '100%', display: 'block', position: i === 0 ? 'relative' : 'absolute', inset: 0, opacity: i === view ? 1 : 0, transform: `scale(${zoom})`, transformOrigin: 'center' }} />
        ))}
        <span className="w-compare-tag" style={{ right: 14 }}>{`Vista ${view + 1} / ${n} — 360°`}</span>
        {/* zoom vertical — stopPropagation para que usarlo no dispare el arrastre de rotación */}
        <div className="w-turntable-zoom" onPointerDown={(e) => e.stopPropagation()}>
          <span aria-hidden="true">+</span>
          <input
            type="range" className="w-turntable-zoom-slider" orient="vertical"
            min={1} max={2.5} step={0.05} value={zoom}
            onChange={(e) => setZoom(Number(e.target.value))}
            aria-label={`Zoom de ${title}`}
          />
          <span aria-hidden="true">−</span>
        </div>
      </div>
      <div className="w-turntable-bar">
        <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
          <path d="M13.5 8a5.5 5.5 0 1 1-1.61-3.89M13.5 1.5v3h-3" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
        <input
          type="range" className="w-turntable-slider"
          min={0} max={n} step={1} value={idx}
          onChange={(e) => setIdx(Number(e.target.value))}
          aria-label={`Rotar vista de ${title}`}
        />
      </div>
    </div>
  );
}

window.ProjectTurntable = ProjectTurntable;

// Project detail modal — opens on card click. Larger image + extended description + specs.
function ProjectModal({ project, onClose, onNavigate }) {
  const { Tag, Badge, Button } = window.ADOSDesignSystem_5aafbb;
  const reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  const [shown, setShown] = React.useState(false);

  React.useEffect(() => {
    if (!project) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    const id = requestAnimationFrame(() => setShown(true));
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.style.overflow = prevOverflow;
      cancelAnimationFrame(id);
      setShown(false);
    };
  }, [project]);

  if (!project) return null;
  const p = project;

  const specs = [
    ['Nivel de detalle', p.lod],
    ['Ubicación', p.location],
    ['Año', p.year],
    ['Software', (p.software || []).join(' · ')],
    ...(p.result ? [['Resultado', p.result]] : []),
  ];

  const close = (e) => { if (e.target === e.currentTarget) onClose(); };

  // Con visor 360° el modal se apila en vertical (imagen a lo ancho, info abajo);
  // sin visor conserva el split lado a lado.
  const hasTurntable = !!(p.turntable && p.turntable.length);

  return (
    <div
      onMouseDown={close}
      role="dialog" aria-modal="true" aria-label={p.title}
      style={{
        position: 'fixed', inset: 0, zIndex: 90,
        display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24,
        background: shown ? 'rgba(10,14,18,0.66)' : 'rgba(10,14,18,0)',
        backdropFilter: shown ? 'blur(6px)' : 'none', WebkitBackdropFilter: shown ? 'blur(6px)' : 'none',
        transition: reduce ? 'none' : 'background 240ms var(--ease-standard), backdrop-filter 240ms',
      }}
    >
      <div className={hasTurntable ? undefined : 'w-split'} style={{
        width: hasTurntable ? 'min(880px, 100%)' : 'min(1040px, 100%)', maxHeight: '90vh', overflow: 'auto',
        background: 'var(--surface)', border: '1px solid var(--border-strong)',
        borderRadius: 'var(--radius-ui)', boxShadow: 'var(--shadow-overlay)',
        gap: 0,
        opacity: shown ? 1 : 0,
        transform: shown || reduce ? 'none' : 'translateY(16px) scale(0.985)',
        transition: reduce ? 'none' : 'opacity 260ms var(--ease-out), transform 260ms var(--ease-out)',
      }}>
        {/* image side — 0px radius per brand rules */}
        {hasTurntable ? (
          <div style={{ position: 'relative' }}>
            <ProjectTurntable frames={p.turntable} title={p.title} />
            <div style={{ position: 'absolute', left: 16, top: 16, display: 'flex', gap: 8 }}>
              <Tag tone="amber">{p.discipline}</Tag>
              <Tag tone="steel">{p.lod}</Tag>
            </div>
          </div>
        ) : (
          <div style={{ position: 'relative', minHeight: 'clamp(240px, 42vw, 420px)', background: 'var(--bg-deep)' }}>
            <div style={{ position: 'absolute', inset: 0, backgroundImage: `url(${p.img})`, backgroundSize: 'cover', backgroundPosition: 'center' }} />
            <div style={{ position: 'absolute', left: 16, bottom: 16, display: 'flex', gap: 8 }}>
              <Tag tone="amber">{p.discipline}</Tag>
              <Tag tone="outline">{p.lod}</Tag>
            </div>
          </div>
        )}

        {/* content side */}
        <div style={{ padding: '32px 34px', display: 'flex', flexDirection: 'column' }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16, marginBottom: 14 }}>
            <Badge status="success" dot>Entregado</Badge>
            <button type="button" aria-label="Cerrar" onClick={onClose}
              style={{ width: 36, height: 36, flex: 'none', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', background: 'transparent', border: '1px solid var(--border-strong)', borderRadius: 'var(--radius-ui)', color: 'var(--text)', cursor: 'pointer' }}>
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"/></svg>
            </button>
          </div>

          <h2 style={{ fontSize: 30, letterSpacing: '-0.03em', lineHeight: 1.08, margin: '0 0 14px' }}>{p.title}</h2>
          <p style={{ margin: '0 0 24px', color: 'var(--text-muted)', fontSize: 15, lineHeight: 1.65 }}>{p.long || p.summary}</p>

          {/* disciplines involved */}
          <div style={{ fontSize: '0.7rem', textTransform: 'uppercase', letterSpacing: '0.1em', color: 'var(--text-faint)', marginBottom: 10 }}>Disciplinas</div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 26 }}>
            {(p.disciplines || []).map((d) => <Tag key={d} tone="steel">{d}</Tag>)}
          </div>

          {/* technical specs */}
          <div style={{ border: '1px solid var(--border)', borderRadius: 'var(--radius-ui)', overflow: 'hidden', marginBottom: 26 }}>
            {specs.map(([k, v], i) => (
              <div key={k} style={{ display: 'flex', justifyContent: 'space-between', gap: 16, padding: '13px 16px', borderTop: i ? '1px solid var(--border)' : 'none', fontSize: 13.5 }}>
                <span style={{ color: 'var(--text-faint)' }}>{k}</span>
                <span style={{ fontFamily: 'var(--font-display)', fontWeight: 500, textAlign: 'right' }}>{v}</span>
              </div>
            ))}
          </div>

          <div style={{ marginTop: 'auto', display: 'flex', gap: 12 }}>
            <Button variant="primary" onClick={() => { onClose(); onNavigate && onNavigate('contact'); }}>Solicitar proyecto similar</Button>
            <Button variant="ghost" onClick={onClose}>Cerrar</Button>
          </div>
        </div>
      </div>
    </div>
  );
}

window.ProjectModal = ProjectModal;
