/* Feature Explorer — a full-screen modal opened from the "Explore Features"
   CTA in BuiltForSurgeons. Walks through real screenshots pulled from the
   product demo video, with hoverable/tappable pins over the areas that
   matter, each explaining what that part of the app is for. */

const FEATURES = [
  {
    id: 'procedures',
    title: 'Every procedure, organized by specialty',
    img: 'assets/feature-shots/procedures.jpg',
    hotspots: [
      { x: 57, y: 25, title: 'Instant search', body: 'Find any procedure by name in seconds — search spans your entire library.' },
      { x: 15, y: 30, title: 'Organized by specialty', body: 'Procedures are grouped by subspecialty — Arthroplasty, Trauma, Spine, Sports Medicine, and more.' },
      { x: 33, y: 44, title: 'One-click procedures', body: 'Every procedure template is ready to open instantly.' },
      { x: 92, y: 37, title: 'Attach a surgeon first', body: "Pick the operating surgeon before opening — the whole panel adapts to their preferences." },
      { x: 6, y: 58, title: 'Everything, one click away', body: 'Surgeons, Evidence, Videos, Notes, and Templates — all in the left rail.' },
    ],
  },
  {
    id: 'reference',
    title: 'Complete surgical reference, in one place',
    img: 'assets/feature-shots/reference.jpg',
    hotspots: [
      { x: 57, y: 22, title: 'Ten tabs, one procedure', body: 'Positioning, Steps, X-Rays, Case Cart, Implants, Pearls, Post-Op, Evidence, Videos — everything about this procedure lives here.' },
      { x: 38, y: 15, title: 'Reconfigures per surgeon', body: 'Pick the operating surgeon and every preference panel updates instantly.' },
      { x: 78, y: 41, title: 'Positioning preview', body: 'See patient position at a glance before diving into full details.' },
      { x: 54, y: 72, title: 'Pearls & pitfalls', body: 'Technique tips and common mistakes, captured from real cases.' },
      { x: 78, y: 72, title: 'Post-op plan', body: 'Weight-bearing status, brace, PT, and DVT prophylaxis at a glance.' },
    ],
  },
  {
    id: 'positioning',
    title: 'Patient positioning at a glance',
    img: 'assets/feature-shots/positioning.jpg',
    hotspots: [
      { x: 58, y: 34, title: 'Full reference photo', body: 'A clear visual for the room — printable or glanceable on a second screen.' },
      { x: 58, y: 51, title: 'Position library', body: 'Every standard OR position, one tap to switch — Supine, Prone, Lateral, Beach Chair, and more.' },
      { x: 58, y: 66, title: 'Step-by-step setup', body: 'Bumps, posts, tourniquet, and anesthesia — documented exactly how this surgeon likes it.' },
      { x: 58, y: 88, title: 'Draping preferences', body: 'Surgeon-specific draping notes, right below positioning.' },
    ],
  },
  {
    id: 'import',
    title: 'AI-powered op report import',
    img: 'assets/feature-shots/import.jpg',
    hotspots: [
      { x: 40, y: 20, title: 'Paste any op report', body: 'Works from a dictated note, EHR export, or free text — no special formatting needed.' },
      { x: 73, y: 32, title: 'Or upload a file', body: 'Accepts .txt, .pdf, and .doc files directly.' },
      { x: 50, y: 55, title: 'Drop in the raw dictation', body: 'Paste the full operative report text directly.' },
      { x: 30, y: 79, title: 'Auto-extracts everything', body: 'Positioning, anesthesia, tourniquet, draping, steps, implants, post-op, and sutures — pulled automatically.' },
      { x: 74, y: 85, title: 'One click to structure it', body: 'AI extracts the data, then you confirm and review before saving.' },
    ],
  },
  {
    id: 'quickmode',
    title: 'OR Quick Mode — live intraoperative checklist',
    img: 'assets/feature-shots/quickmode.jpg',
    hotspots: [
      { x: 34, y: 12, title: 'Live intraoperative mode', body: 'One tap turns the procedure into a distraction-free, live checklist for the OR.' },
      { x: 57, y: 26, title: 'Indications up top', body: 'Key clinical indications surfaced immediately, no scrolling.' },
      { x: 42, y: 57, title: 'Positioning, still one glance away', body: 'Full positioning detail stays visible even in quick mode.' },
      { x: 57, y: 85, title: 'Live step tracking', body: 'Track steps complete in real time without breaking focus.' },
    ],
  },
  {
    id: 'evidence',
    title: 'Instant AI evidence search, mid-case',
    img: 'assets/feature-shots/evidence.jpg',
    hotspots: [
      { x: 90, y: 6, title: 'Evidence search, built in', body: 'Ask clinical questions without ever leaving the procedure. Switch between Gemini and Claude.' },
      { x: 71, y: 25, title: 'Go deeper', body: 'Escalate to a full literature search in Open Evidence when you need more.' },
      { x: 88, y: 47, title: 'Curated for this case', body: 'Pre-loaded evidence topics specific to Total Knee Arthroplasty.' },
    ],
  },
  {
    id: 'xray-annotation',
    title: 'X-ray annotation & pre-op planning',
    img: 'assets/feature-shots/xray-annotation.jpg',
    hotspots: [
      { x: 5, y: 21, title: 'Full annotation toolset', body: 'Freehand draw, fragment outline, arrows, lines, and text labels.' },
      { x: 5, y: 67, title: 'Implant & clamp library', body: 'Drag-place screws, plates, IM nails, K-wires, and clamps as editable vector stamps.' },
      { x: 48, y: 45, title: 'Non-destructive layers', body: 'Annotate directly on the X-ray — the original image is never modified.' },
      { x: 92, y: 12, title: 'Full undo history', body: 'Undo, redo, duplicate, and clear — every change is reversible.' },
    ],
  },
  {
    id: 'ai-assistant',
    title: 'AI Assistant — your surgical copilot',
    img: 'assets/feature-shots/ai-assistant.jpg',
    hotspots: [
      { x: 87, y: 6, title: 'Connected to your procedure', body: 'Claude AI has context on the current procedure, surgeon, and steps.' },
      { x: 91, y: 15, title: 'Ask in plain language', body: 'Type any question about the case — steps, pitfalls, implants, post-op.' },
      { x: 85, y: 36, title: 'Clinically precise answers', body: "Grounded in the procedure's own data — positioning, steps, and implants already on file." },
      { x: 86, y: 90, title: 'Always one click away', body: 'Open the panel from anywhere in the app with the AI button in the top bar.' },
    ],
  },
  {
    id: 'pdf-annotation',
    title: 'Highlight and annotate evidence papers',
    img: 'assets/feature-shots/pdf-annotation.jpg',
    hotspots: [
      { x: 6, y: 9, title: 'Cursor, highlight, and note tools', body: 'Switch between reading, highlighting, and annotating without leaving the page.' },
      { x: 91, y: 9, title: 'Every annotation tracked', body: 'See exactly how many highlights and notes are on each page.' },
      { x: 41, y: 37, title: 'Highlight what matters', body: 'Click and drag over any passage to mark it for later.' },
      { x: 85, y: 45, title: 'Drop a note anywhere', body: 'Pin context-specific notes directly on the paper — visible next time you open it.' },
    ],
  },
];

function FeatureHotspot({ spot, accent, isOpen, onOpen, onClose }) {
  const align = spot.x < 30 ? 'left' : spot.x > 70 ? 'right' : 'center';
  const vAlign = spot.y < 50 ? 'below' : 'above';

  const popupStyle = {
    position: 'absolute',
    width: 220,
    padding: '12px 14px',
    background: '#0e1525',
    color: '#f0f1f3',
    borderRadius: 10,
    boxShadow: '0 20px 40px -12px rgba(0,0,0,0.5)',
    fontSize: 12.5,
    lineHeight: 1.5,
    zIndex: 10,
    pointerEvents: 'none',
  };
  if (vAlign === 'below') { popupStyle.top = 'calc(100% + 12px)'; } else { popupStyle.bottom = 'calc(100% + 12px)'; }
  if (align === 'left') { popupStyle.left = 0; }
  else if (align === 'right') { popupStyle.right = 0; }
  else { popupStyle.left = '50%'; popupStyle.transform = 'translateX(-50%)'; }

  return (
    <div
      onMouseEnter={onOpen}
      onMouseLeave={onClose}
      onClick={(e) => { e.stopPropagation(); isOpen ? onClose() : onOpen(); }}
      className={`feature-hotspot${isOpen ? ' is-open' : ''}`}
      style={{
        position: 'absolute',
        left: `${spot.x}%`, top: `${spot.y}%`,
        transform: 'translate(-50%, -50%)',
        width: 24, height: 24, borderRadius: 12,
        background: accent,
        border: '2px solid #fff',
        cursor: 'pointer',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        zIndex: isOpen ? 20 : 5,
      }}>
      <span style={{ width: 6, height: 6, borderRadius: 3, background: '#fff', flexShrink: 0 }} />
      {isOpen && (
        <div style={popupStyle}>
          <div style={{ fontWeight: 600, fontSize: 13, marginBottom: 4, color: '#fff' }}>{spot.title}</div>
          <div style={{ color: 'rgba(240,241,243,0.75)' }}>{spot.body}</div>
        </div>
      )}
    </div>
  );
}

function FeatureExplorerModal({ accent }) {
  const [open, setOpen] = React.useState(false);
  const [index, setIndex] = React.useState(0);
  const [openSpot, setOpenSpot] = React.useState(null);
  const isMobile = useIsMobile();

  React.useEffect(() => {
    window.openFeatureExplorer = () => { setIndex(0); setOpenSpot(null); setOpen(true); };
    return () => { delete window.openFeatureExplorer; };
  }, []);

  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => {
      if (e.key === 'Escape') setOpen(false);
      if (e.key === 'ArrowRight') go(1);
      if (e.key === 'ArrowLeft') go(-1);
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
    // eslint-disable-next-line
  }, [open, index]);

  function go(delta) {
    setOpenSpot(null);
    setIndex((i) => (i + delta + FEATURES.length) % FEATURES.length);
  }

  if (!open) return null;

  const feature = FEATURES[index];

  return (
    <div
      onClick={() => setOpen(false)}
      style={{
        position: 'fixed', inset: 0, zIndex: 1000,
        background: 'rgba(8, 10, 14, 0.85)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: isMobile ? 12 : 28,
      }}>
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          width: '100%', maxWidth: 1040, minWidth: 0,
          maxHeight: '92vh',
          background: 'var(--surface)',
          borderRadius: 18,
          boxShadow: '0 40px 100px -20px rgba(0,0,0,0.7)',
          overflow: 'hidden',
          display: 'flex', flexDirection: 'column',
        }}>
        {/* Header */}
        <div style={{
          padding: isMobile ? '16px 16px 12px' : '22px 28px 16px',
          display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16,
          borderBottom: '1px solid var(--border)',
        }}>
          <div style={{ minWidth: 0 }}>
            <div style={{
              fontFamily: '"Geist Mono", ui-monospace, monospace',
              fontSize: 11, fontWeight: 600, color: accent, letterSpacing: 1.2,
              textTransform: 'uppercase', marginBottom: 6,
            }}>Explore features · {index + 1} / {FEATURES.length}</div>
            <div style={{ fontSize: isMobile ? 17 : 21, fontWeight: 600, letterSpacing: -0.4, color: 'var(--text)', textWrap: 'balance' }}>
              {feature.title}
            </div>
          </div>
          <button
            onClick={() => setOpen(false)}
            aria-label="Close feature explorer"
            style={{
              width: 32, height: 32, borderRadius: 16, flexShrink: 0,
              border: '1px solid var(--btn-ghost-border)', background: 'var(--btn-ghost-bg)',
              color: 'var(--text)', fontSize: 15, cursor: 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>✕</button>
        </div>

        {/* Screenshot + hotspots */}
        <div style={{
          position: 'relative', flex: 1, overflow: 'auto',
          background: '#0a0c11', padding: isMobile ? 12 : 24,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <div style={{ position: 'relative', width: '100%', maxWidth: 920 }}>
            <img
              src={feature.img}
              alt={feature.title}
              style={{ width: '100%', height: 'auto', display: 'block', borderRadius: 10, boxShadow: '0 1px 0 rgba(255,255,255,0.06)' }}
            />
            {feature.hotspots.map((spot, i) => (
              <FeatureHotspot
                key={i}
                spot={spot}
                accent={accent}
                isOpen={openSpot === i}
                onOpen={() => setOpenSpot(i)}
                onClose={() => setOpenSpot((cur) => (cur === i ? null : cur))}
              />
            ))}
          </div>
        </div>

        {/* Footer: prev/next + dots */}
        <div style={{
          padding: isMobile ? '12px 16px' : '16px 28px',
          borderTop: '1px solid var(--border)',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 14,
        }}>
          <button
            onClick={() => go(-1)}
            style={{
              padding: '9px 14px', fontSize: 13, fontWeight: 600, fontFamily: 'inherit',
              border: '1px solid var(--btn-ghost-border)', background: 'var(--btn-ghost-bg)',
              color: 'var(--text)', borderRadius: 9, cursor: 'pointer',
              display: 'inline-flex', alignItems: 'center', gap: 6,
            }}>← {isMobile ? '' : 'Prev'}</button>

          <div style={{ display: 'flex', gap: 7 }}>
            {FEATURES.map((f, i) => (
              <button
                key={f.id}
                onClick={() => { setOpenSpot(null); setIndex(i); }}
                aria-label={f.title}
                style={{
                  width: i === index ? 20 : 7, height: 7, borderRadius: 4,
                  border: 'none', padding: 0, cursor: 'pointer',
                  background: i === index ? accent : 'var(--border-strong)',
                  transition: 'width 0.15s ease, background 0.15s ease',
                }} />
            ))}
          </div>

          <button
            onClick={() => go(1)}
            style={{
              padding: '9px 14px', fontSize: 13, fontWeight: 600, fontFamily: 'inherit',
              border: 'none', background: accent, color: '#fff', borderRadius: 9, cursor: 'pointer',
              display: 'inline-flex', alignItems: 'center', gap: 6,
            }}>{isMobile ? '' : 'Next'} →</button>
        </div>
      </div>
    </div>
  );
}
