// Project detail — full-width page (not a slide-over).
// Driven by the parent via prop; closes via onClose, switches via onSelect.
// Hacker palette: dark terminal-paper, phosphor green primary.

// Shared responsive hook — used by both ProjectDetail and DossierMain
function useIsMobile(breakpoint = 768) {
  const [mobile, setMobile] = React.useState(
    typeof window !== 'undefined' && window.innerWidth <= breakpoint
  );
  React.useEffect(() => {
    const check = () => setMobile(window.innerWidth <= breakpoint);
    window.addEventListener('resize', check);
    return () => window.removeEventListener('resize', check);
  }, [breakpoint]);
  return mobile;
}

const detailStyles = {
  page: {
    minHeight: '100vh',
    background: 'var(--bg)',
    fontFamily: "'JetBrains Mono', monospace",
    color: 'var(--ink)',
  },
  topbar: {
    position: 'sticky', top: 0, zIndex: 20,
    background: '#000',
    borderBottom: '1px solid var(--green)',
    padding: '12px 24px',
    display: 'flex', alignItems: 'center', gap: 14,
    fontSize: 11, letterSpacing: 1.4, color: 'var(--green)',
  },
  toolbar: {
    background: 'var(--paper-2)',
    borderBottom: '1px solid var(--line-2)',
    padding: '14px 32px',
    display: 'flex', justifyContent: 'space-between', alignItems: 'center',
    gap: 16, flexWrap: 'wrap',
  },
  toolGroup: { display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' },

  // Floating back button — stays in view as page scrolls
  floatingBack: {
    position: 'fixed',
    bottom: 32,
    left: 32,
    zIndex: 100,
    background: 'var(--green)',
    color: '#000',
    fontFamily: "'JetBrains Mono', monospace",
    fontSize: 12,
    fontWeight: 600,
    letterSpacing: 0.8,
    padding: '10px 18px',
    border: 'none',
    cursor: 'pointer',
    boxShadow: '4px 4px 0 rgba(57,255,122,0.25)',
    transition: 'transform .1s, box-shadow .1s',
  },

  body: {
    maxWidth: 980, margin: '0 auto',
    padding: '40px 32px 80px',
  },

  docHead: {
    paddingBottom: 24,
    borderBottom: '2px solid var(--line-2)',
    marginBottom: 28,
  },
  twId: {
    fontSize: 11, letterSpacing: 1.4, color: 'var(--green)',
    marginBottom: 12,
  },
  title: {
    fontFamily: "'Inter', sans-serif", fontSize: 44, fontWeight: 700,
    letterSpacing: -1.2, margin: 0, lineHeight: 1.05, color: '#fff',
  },
  blurb: {
    fontFamily: "'Inter', sans-serif", fontSize: 17, lineHeight: 1.65,
    color: 'var(--ink)', marginTop: 16, maxWidth: 760,
  },
  metaRow: { display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 18 },
  tag: {
    fontSize: 12, letterSpacing: 0.4, color: 'var(--green)',
    border: '1px solid var(--line-2)', background: '#000',
    padding: '3px 9px', borderRadius: 2,
    fontFamily: "'JetBrains Mono', monospace",
  },

  callout: {
    fontFamily: "'Inter', sans-serif", fontSize: 16, lineHeight: 1.7,
    background: 'var(--paper-2)',
    borderLeft: '3px solid var(--green)',
    padding: '16px 20px', color: 'var(--ink)',
    border: '1px solid var(--line-2)',
  },
  body2: {
    fontFamily: "'Inter', sans-serif",
    fontSize: 16, lineHeight: 1.7, color: 'var(--ink)',
  },
  list: {
    margin: '4px 0 0', padding: '0 0 0 20px',
    fontFamily: "'Inter', sans-serif", fontSize: 16, lineHeight: 1.75,
    color: 'var(--ink)',
  },
  artifactRow: { display: 'flex', flexWrap: 'wrap', gap: 10 },
  artifact: {
    fontSize: 12, color: 'var(--green)',
    border: '1px solid var(--green)', background: '#000',
    padding: '8px 12px', borderRadius: 2,
    fontFamily: "'JetBrains Mono', monospace",
  },

  // Rich content section styles
  figure: {
    margin: '18px 0',
    background: '#0a0c10',
    border: '1px solid var(--line-2)',
    borderRadius: 6,
    overflow: 'hidden',
  },
  figImg: {
    width: '100%',
    height: 'auto',
    display: 'block',
  },
  figCaption: {
    padding: '10px 14px',
    fontSize: 13,
    color: 'var(--dim)',
    borderTop: '1px dashed var(--line-2)',
    fontFamily: "'JetBrains Mono', monospace",
  },
  codeBlock: {
    background: '#0a0c10',
    color: '#c5f0c8',
    padding: '16px 18px',
    borderRadius: 6,
    overflow: 'auto',
    border: '1px solid var(--line-2)',
    fontSize: 13,
    lineHeight: 1.6,
    fontFamily: "'JetBrains Mono', monospace",
    whiteSpace: 'pre-wrap',
    wordBreak: 'break-word',
  },
  codeTitle: {
    fontSize: 11,
    letterSpacing: 0.6,
    color: 'var(--dim)',
    marginBottom: 6,
    fontFamily: "'JetBrains Mono', monospace",
  },
  disclosure: {
    margin: '12px 0',
    border: '1px solid var(--line-2)',
    borderRadius: 6,
    overflow: 'hidden',
  },
  disclosureSummary: {
    padding: '12px 16px',
    background: 'var(--paper-2)',
    cursor: 'pointer',
    fontSize: 13,
    color: 'var(--green)',
    fontFamily: "'JetBrains Mono', monospace",
    letterSpacing: 0.4,
    userSelect: 'none',
  },
  // Slider styles
  sliderFrame: {
    position: 'relative',
  },
  sliderControls: {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    gap: 12,
    padding: '10px 14px',
    background: 'var(--paper-2)',
    borderTop: '1px solid var(--line-2)',
  },
  sliderBtn: {
    border: '1px solid var(--line-2)',
    background: '#000',
    color: 'var(--green)',
    borderRadius: 2,
    padding: '6px 14px',
    fontSize: 11,
    cursor: 'pointer',
    fontFamily: "'JetBrains Mono', monospace",
    letterSpacing: 0.6,
  },
  sliderDots: {
    display: 'flex', gap: 6, alignItems: 'center',
  },
  sliderDot: {
    width: 10, height: 10, borderRadius: '50%',
    border: '1px solid var(--line-2)',
    background: 'transparent',
    padding: 0, cursor: 'pointer',
    transition: 'background .15s',
  },
  sliderDotActive: {
    background: 'var(--green)',
  },
  video: {
    width: '100%',
    borderRadius: 6,
    border: '1px solid var(--line-2)',
    background: '#000',
  },

  footerNav: {
    marginTop: 56, paddingTop: 24,
    borderTop: '2px solid var(--line-2)',
    display: 'grid', gridTemplateColumns: '1fr 1fr',
    gap: 16,
  },
  navCard: {
    border: '1px solid var(--line-2)',
    background: 'var(--paper-2)',
    padding: '16px 18px',
    cursor: 'pointer',
    transition: 'border-color .12s, background .12s, transform .12s',
  },
  navCardLabel: {
    fontSize: 10, letterSpacing: 1.4, color: 'var(--dim)',
    textTransform: 'uppercase', marginBottom: 6,
  },
  navCardTitle: {
    fontFamily: "'Inter', sans-serif", fontSize: 16,
    color: '#fff', fontWeight: 600,
  },
};

// ─── Image Slider sub-component ───────────────────────────────────────
function ImageSlider({ images }) {
  const [idx, setIdx] = React.useState(0);
  const ds = detailStyles;
  const count = images.length;

  const show = (i) => setIdx((i + count) % count);

  return (
    <div style={ds.figure}>
      <div style={ds.sliderFrame}>
        {images.map((img, i) => (
          <img
            key={i}
            src={img.src}
            alt={img.alt || ''}
            style={{ ...ds.figImg, display: i === idx ? 'block' : 'none' }}
            loading={i === 0 ? 'eager' : 'lazy'}
          />
        ))}
      </div>
      {count > 1 && (
        <div style={ds.sliderControls}>
          <button style={ds.sliderBtn} onClick={() => show(idx - 1)} aria-label="Previous">← PREV</button>
          <div style={ds.sliderDots}>
            {images.map((_, i) => (
              <button
                key={i}
                style={{ ...ds.sliderDot, ...(i === idx ? ds.sliderDotActive : {}) }}
                onClick={() => show(i)}
                aria-label={`Show image ${i + 1}`}
              />
            ))}
          </div>
          <button style={ds.sliderBtn} onClick={() => show(idx + 1)} aria-label="Next">NEXT →</button>
        </div>
      )}
      {images[idx]?.caption && (
        <div style={ds.figCaption}>{images[idx].caption}</div>
      )}
    </div>
  );
}

// ─── Code Disclosure sub-component ────────────────────────────────────
function CodeDisclosure({ label, code, language }) {
  const [open, setOpen] = React.useState(false);
  const ds = detailStyles;

  return (
    <div style={ds.disclosure}>
      <div
        style={ds.disclosureSummary}
        onClick={() => setOpen(!open)}
        role="button"
        tabIndex={0}
        onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setOpen(!open); } }}
      >
        {open ? '▾' : '▸'} {label || 'View source code'}
      </div>
      {open && (
        <pre style={{ ...ds.codeBlock, margin: 0, borderRadius: 0, borderTop: '1px solid var(--line-2)' }}>
          <code>{code}</code>
        </pre>
      )}
    </div>
  );
}

// ─── Rich section renderer ────────────────────────────────────────────
function RichContentBlock({ block, mobile }) {
  const ds = detailStyles;

  switch (block.type) {
    case 'paragraph':
      return <p style={{ ...ds.body2, fontSize: mobile ? 14 : 16, marginTop: 8, marginBottom: 8 }}>{block.text}</p>;

    case 'list':
      const ListTag = block.ordered ? 'ol' : 'ul';
      return (
        <ListTag style={{ ...ds.list, fontSize: mobile ? 14 : 16 }}>
          {block.items.map((item, i) => <li key={i} style={{ marginBottom: 6 }}>{item}</li>)}
        </ListTag>
      );

    case 'image':
      return (
        <div style={{ ...ds.figure, ...(block.maxWidth ? { maxWidth: block.maxWidth } : {}) }}>
          <img src={block.src} alt={block.alt || ''} style={ds.figImg} loading="lazy" />
          {block.caption && <div style={ds.figCaption}>{block.caption}</div>}
        </div>
      );

    case 'slider':
      return <ImageSlider images={block.images} />;

    case 'code':
      return (
        <div>
          {block.title && <div style={ds.codeTitle}>{block.title}</div>}
          <pre style={{ ...ds.codeBlock, fontSize: mobile ? 12 : 13 }}>
            <code>{block.code}</code>
          </pre>
        </div>
      );

    case 'disclosure':
      return <CodeDisclosure label={block.label} code={block.code} language={block.language} />;

    case 'video':
      return (
        <div style={ds.figure}>
          <video controls style={ds.video} preload="metadata">
            <source src={block.src} type={block.mimeType || 'video/mp4'} />
            Your browser does not support the video tag.
          </video>
          {block.caption && <div style={ds.figCaption}>{block.caption}</div>}
        </div>
      );

    default:
      return null;
  }
}

function ProjectDetail({ project, projects, onClose, onSelect }) {
  const idx = projects.findIndex(p => p.id === project.id);
  const prev = projects[idx - 1];
  const next = projects[idx + 1];
  const d = project.detail || {};
  const ds = detailStyles;
  const mobile = useIsMobile();

  // Esc to close, ←/→ to switch
  React.useEffect(() => {
    const handler = (e) => {
      if (e.key === 'Escape') onClose();
      else if (e.key === 'ArrowLeft' && prev) onSelect(prev.id);
      else if (e.key === 'ArrowRight' && next) onSelect(next.id);
    };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [project.id, prev?.id, next?.id]);

  // Reset scroll when switching projects
  React.useEffect(() => { window.scrollTo({ top: 0, behavior: 'instant' }); }, [project.id]);

  return (
    <div style={ds.page} className="page-enter page-enter-active">
      <div style={{ ...ds.topbar, fontSize: mobile ? 10 : 11, padding: mobile ? '10px 16px' : '12px 24px' }}>
        <span>// TECHNICAL WORK · TW-{String(idx + 1).padStart(3, '0')}</span>
        {!mobile && <span style={{ marginLeft: 'auto', color: 'var(--dim)' }}>ESC · ← → to navigate</span>}
      </div>

      <div style={{ ...ds.toolbar, padding: mobile ? '12px 16px' : '14px 32px', flexDirection: mobile ? 'column' : 'row', alignItems: mobile ? 'stretch' : 'center' }}>
        <div style={{ ...ds.toolGroup, justifyContent: mobile ? 'center' : 'flex-start' }}>
          <button className="navbtn ghost-green" onClick={onClose}>← {mobile ? 'BACK' : 'BACK TO HOME'}</button>
        </div>
        <div style={{ ...ds.toolGroup, justifyContent: 'center', flexWrap: 'wrap' }}>
          <button className="navbtn ghost-green" disabled={!prev} onClick={() => prev && onSelect(prev.id)}>← PREV</button>
          <select
            className="nav-select"
            value={project.id}
            onChange={(e) => onSelect(e.target.value)}
            aria-label="Switch project"
            style={{ flex: mobile ? '1 1 auto' : 'none', minWidth: mobile ? 0 : 'auto' }}
          >
            {projects.map((p, i) => (
              <option key={p.id} value={p.id}>
                {mobile ? `TW-${String(i + 1).padStart(3, '0')}` : `TW-${String(i + 1).padStart(3, '0')} · ${p.title}`}
              </option>
            ))}
          </select>
          <button className="navbtn ghost-green" disabled={!next} onClick={() => next && onSelect(next.id)}>NEXT →</button>
        </div>
        <div style={{ ...ds.toolGroup, justifyContent: mobile ? 'center' : 'flex-end' }}>
          <button className="navbtn ghost-green" onClick={onClose}>✕ CLOSE</button>
        </div>
      </div>

      {/* Floating back button */}
      <button
        style={{
          ...ds.floatingBack,
          bottom: mobile ? 20 : 32,
          left: mobile ? 20 : 32,
          fontSize: mobile ? 11 : 12,
          padding: mobile ? '8px 14px' : '10px 18px',
        }}
        onClick={onClose}
        onMouseEnter={e => { e.currentTarget.style.transform = 'translate(-2px,-2px)'; e.currentTarget.style.boxShadow = '6px 6px 0 rgba(57,255,122,0.35)'; }}
        onMouseLeave={e => { e.currentTarget.style.transform = 'none'; e.currentTarget.style.boxShadow = '4px 4px 0 rgba(57,255,122,0.25)'; }}
      >← BACK</button>

      <div style={{ ...ds.body, padding: mobile ? '24px 20px 64px' : '40px 32px 80px' }}>
        <div style={ds.docHead}>
          <div style={{ ...ds.twId, fontSize: mobile ? 10 : 11 }}>TW-{String(idx + 1).padStart(3, '0')} · {project.kind.toUpperCase()}</div>
          <h1 style={{ ...ds.title, fontSize: mobile ? 32 : 44 }}>{project.title}</h1>
          <p style={{ ...ds.blurb, fontSize: mobile ? 15 : 17 }}>{project.blurb}</p>
          <div style={ds.metaRow}>
            {project.tags.map(t => <span key={t} style={{ ...ds.tag, fontSize: mobile ? 11 : 12 }}>{t}</span>)}
          </div>
        </div>

        {d.objective ? (
          <>
            <div className="h-section"><span>§ Objective</span></div>
            <div style={{ ...ds.callout, fontSize: mobile ? 14 : 16, padding: mobile ? '14px 16px' : '16px 20px' }}>{d.objective}</div>
          </>
        ) : null}

        {d.approach?.length ? (
          <>
            <div className="h-section"><span>§ Approach</span><span className="h-count">{d.approach.length} steps</span></div>
            <ol style={{ ...ds.list, fontSize: mobile ? 14 : 16 }}>
              {d.approach.map((step, i) => <li key={i} style={{ marginBottom: 8 }}>{step}</li>)}
            </ol>
          </>
        ) : null}

        {d.outcomes?.length ? (
          <>
            <div className="h-section"><span>§ Outcomes</span></div>
            <ul style={{ ...ds.list, fontSize: mobile ? 14 : 16 }}>
              {d.outcomes.map((o, i) => <li key={i} style={{ marginBottom: 8 }}>{o}</li>)}
            </ul>
          </>
        ) : null}

        {d.learned ? (
          <>
            <div className="h-section"><span>§ What I learned</span></div>
            <div style={{ ...ds.body2, fontSize: mobile ? 14 : 16 }}>{d.learned}</div>
          </>
        ) : null}

        {/* ─── Rich content sections ──────────────────────────────── */}
        {d.sections?.map((section, si) => (
          <div key={si}>
            {section.heading && (
              <div className="h-section"><span>§ {section.heading}</span></div>
            )}
            {section.content?.map((block, bi) => (
              <RichContentBlock key={bi} block={block} mobile={mobile} />
            ))}
          </div>
        ))}

        {d.artifacts?.length ? (
          <>
            <div className="h-section"><span>§ Artifacts</span></div>
            <div style={ds.artifactRow}>
              {d.artifacts.map((a, i) => <span key={i} style={{ ...ds.artifact, fontSize: mobile ? 11 : 12 }}>{a}</span>)}
            </div>
          </>
        ) : null}

        <div style={{
          ...ds.footerNav,
          gridTemplateColumns: mobile ? '1fr' : '1fr 1fr',
          gap: mobile ? 12 : 16,
        }}>
          {prev ? (
            <div
              style={ds.navCard}
              onClick={() => onSelect(prev.id)}
              onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--green)'; e.currentTarget.style.transform = 'translateX(-3px)'; }}
              onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--line-2)'; e.currentTarget.style.transform = 'translateX(0)'; }}
            >
              <div style={{ ...ds.navCardLabel, fontSize: mobile ? 9 : 10 }}>← Previous · TW-{String(idx).padStart(3, '0')}</div>
              <div style={{ ...ds.navCardTitle, fontSize: mobile ? 14 : 16 }}>{prev.title}</div>
            </div>
          ) : !mobile ? <div /> : null}
          {next ? (
            <div
              style={{ ...ds.navCard, textAlign: mobile ? 'left' : 'right' }}
              onClick={() => onSelect(next.id)}
              onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--green)'; e.currentTarget.style.transform = mobile ? 'translateY(-2px)' : 'translateX(3px)'; }}
              onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--line-2)'; e.currentTarget.style.transform = 'none'; }}
            >
              <div style={{ ...ds.navCardLabel, fontSize: mobile ? 9 : 10 }}>Next · TW-{String(idx + 2).padStart(3, '0')} →</div>
              <div style={{ ...ds.navCardTitle, fontSize: mobile ? 14 : 16 }}>{next.title}</div>
            </div>
          ) : !mobile ? <div /> : null}
        </div>

        <div style={{ marginTop: 32, textAlign: 'center' }}>
        </div>
      </div>
    </div>
  );
}

window.ProjectDetail = ProjectDetail;
