/* Resident guide — "How to" page. Step-by-step walkthrough for new
   users getting up to speed on OrthoVaultOS. Reuses the marketing site
   Nav + Footer and the same theme tokens, with a left-side TOC and
   numbered sections on the right. */

const GUIDE_SECTIONS = [
  {
    id: 'getting-started',
    title: 'Getting started',
    body: [
      'Download OrthoVaultOS for macOS or Windows from the home page. The app is signed and notarized — no extra security prompts on either platform.',
      'Create a free account and you\'re in — the free tier covers 1 surgeon and 1 procedure with no time limit, so you can try the full app on a real case before upgrading.',
      'If you sign in, your library — procedures, steps, surgeon preferences, implants, evidence links, videos, and notes — syncs to the cloud and stays current across every device you use. Upgrade to Professional for cloud photo sync too.'
    ]
  },
  {
    id: 'search-pick',
    title: 'Search and open a procedure',
    body: [
      'Hit ⌘K (Mac) or Ctrl+K (Windows) from anywhere to open Quick Search. Start typing — TKA, ACL, distal radius, whatever — to search across procedures, surgeons, steps, and files.',
      'Click the result to open the procedure view, or browse the sidebar by subspecialty. Click the star on any procedure to pin it to Favorites for next time.',
      'Don\'t see what you need? Use "+ New Procedure" in the sidebar to build one from scratch.'
    ]
  },
  {
    id: 'surgeon-profile',
    title: 'Add a surgeon profile',
    body: [
      'Open Surgeons → "+ New Surgeon" and enter their name.',
      'Each surgeon gets their own overrides on top of the standard template: preferred steps, instruments, implants, positioning, and post-op protocol — plus the pearls they always mention.',
      'On the procedure view, pick the surgeon from the dropdown in the header and the whole panel reconfigures to their preferences.'
    ]
  },
  {
    id: 'mid-case',
    title: 'Reference mid-case',
    body: [
      'Pull the iPad or scrubbed-in laptop within glancing distance and switch to OR Mode — a focused, read-only checklist view built for the operating room.',
      'Tap a step to check it off as you go; toggle post-op items (weight-bearing, brace, PT, DVT prophylaxis) and TXA dosing in real time. A progress bar tracks how many steps are complete.',
      'Positioning photos, implant references, and pearls are all one tab away — no need to switch apps or break sterile field.'
    ]
  },
  {
    id: 'annotate',
    title: 'Annotate X-rays and papers',
    body: [
      'On the X-Rays tab, upload an image and click its annotate icon to open the pre-op planning editor — freehand draw, outline a fragment, add arrows or labels, and drag-place implant and clamp stamps with adjustable rotation and size. The original image is never modified.',
      'Uploaded PDFs and Word docs open in a built-in viewer with highlight and note tools — drag over a passage to highlight it, or pin a note to a specific spot on the page. Both persist for next time.'
    ]
  },
  {
    id: 'export-plan',
    title: 'Export and share your work',
    body: [
      'Save a procedure-surgeon combination as a reusable template from the Templates page — steps, overrides, instruments, implants, evidence links, positioning, and post-op protocol all bundle into one JSON file you can back up or hand off.',
      'Use Borrow Template to pull specific sections from another surgeon\'s template into the one you\'re building, without overwriting the rest.',
      'You can also export your entire library as a JSON file from Account → Data & Privacy — useful if you\'re moving institutions or just want a personal backup.'
    ]
  },
  {
    id: 'pearls',
    title: 'Customize and capture pearls',
    body: [
      'Pearls are short, attributable tips — "tension the graft at 30° of flexion", "always start medial with this approach", etc.',
      'After each case, log new pearls in the Pearls & Pitfalls tab and attribute them to the surgeon who taught them. The next resident on rotation walks in already knowing.',
      'Pearls show up automatically when you open the same procedure with that surgeon selected.'
    ]
  },
  {
    id: 'sync',
    title: 'Settings',
    body: [
      'Settings → Appearance lets you switch between light and dark mode — dark suits low-light OR use.',
      'Settings → Cloud Sync shows your sync status and keeps your library current across your own devices when you\'re signed in. It doesn\'t share your library with other users — collaborative sharing with a co-resident is on the roadmap.',
      'Settings → Backup & Restore (desktop) lets you save and restore a full backup snapshot on demand, as an extra safety net alongside cloud sync.'
    ]
  }
];

function ResidentGuideApp() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const accent = t.accent || '#b91c2c';
  const theme = t.theme || 'light';
  const isMobile = useIsMobile();
  const [active, setActive] = React.useState(GUIDE_SECTIONS[0].id);

  React.useEffect(() => {
    document.body.setAttribute('data-theme', theme);
    return () => { document.body.removeAttribute('data-theme'); };
  }, [theme]);

  // Track which section is closest to the top of the viewport.
  React.useEffect(() => {
    const obs = new IntersectionObserver((entries) => {
      const visible = entries.filter((e) => e.isIntersecting).sort((a, b) => a.boundingClientRect.top - b.boundingClientRect.top);
      if (visible[0]) setActive(visible[0].target.id);
    }, { rootMargin: '-20% 0px -60% 0px', threshold: 0 });
    GUIDE_SECTIONS.forEach((s) => {
      const el = document.getElementById(s.id);
      if (el) obs.observe(el);
    });
    return () => obs.disconnect();
  }, []);

  return (
    <div data-theme={theme} style={{
      fontFamily: '"Geist", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
      color: 'var(--text)',
      background: 'var(--bg)',
      minHeight: '100vh',
    }}>
      <Nav accent={accent} />

      {/* Header */}
      <section style={{
        padding: isMobile ? '40px 20px 24px' : '72px 28px 32px',
        position: 'relative',
        overflow: 'hidden'
      }}>
        <div aria-hidden="true" style={{
          position: 'absolute', inset: 0, pointerEvents: 'none',
          background: `radial-gradient(40% 70% at 80% 0%, ${accent}1a, transparent 60%)`,
        }}></div>
        <div style={{ position: 'relative', maxWidth: 1200, margin: '0 auto' }}>
          <div style={{
            fontSize: 11.5, fontWeight: 600, color: accent, letterSpacing: 1.4,
            textTransform: 'uppercase', marginBottom: 14
          }}>Resident guide</div>
          <h1 style={{
            fontSize: isMobile ? 34 : 72, lineHeight: 1.05, letterSpacing: isMobile ? -1.2 : -2.2, fontWeight: 600,
            margin: '0 0 18px', color: 'var(--text)', textWrap: 'balance'
          }}>
            How{' '}
            <span style={{
              color: accent, fontWeight: 600,
              textTransform: 'uppercase', letterSpacing: -0.8
            }}>TO.</span>
          </h1>
          <p style={{
            fontSize: isMobile ? 15.5 : 18, lineHeight: 1.55, color: 'var(--muted)',
            margin: 0, maxWidth: 640, textWrap: 'pretty'
          }}>
            A short walkthrough for using OrthoVaultOS — from your first download to annotating your first X-ray and exporting your first template.
          </p>
        </div>
      </section>

      {/* TOC + sections */}
      <section style={{ padding: isMobile ? '24px 20px 56px' : '32px 28px 96px', borderTop: '1px solid var(--border)' }}>
        <div style={{
          maxWidth: 1200, margin: '0 auto',
          display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '240px 1fr', gap: isMobile ? 28 : 56, alignItems: 'start'
        }}>
          {/* Sticky TOC */}
          <nav style={{ position: isMobile ? 'static' : 'sticky', top: 96, alignSelf: 'start' }}>
            <div style={{
              fontSize: 10.5, fontWeight: 600, color: 'var(--subtle)', letterSpacing: 1.2,
              textTransform: 'uppercase', marginBottom: 14, fontFamily: '"Geist Mono", ui-monospace, monospace'
            }}>Contents</div>
            <ol style={{
              listStyle: 'none', padding: 0, margin: 0,
              display: 'flex', flexDirection: 'column', gap: 4,
              counterReset: 'guide'
            }}>
              {GUIDE_SECTIONS.map((s, i) => {
                const isActive = active === s.id;
                return (
                  <li key={s.id} style={{ counterIncrement: 'guide' }}>
                    <a href={`#${s.id}`} style={{
                      display: 'flex', alignItems: 'baseline', gap: 10,
                      padding: '8px 10px',
                      borderRadius: 8,
                      textDecoration: 'none',
                      color: isActive ? 'var(--text)' : 'var(--muted)',
                      background: isActive ? 'var(--surface)' : 'transparent',
                      fontSize: 13.5, fontWeight: isActive ? 600 : 500,
                      letterSpacing: -0.1,
                      borderLeft: `2px solid ${isActive ? accent : 'transparent'}`,
                      paddingLeft: 12
                    }}>
                      <span style={{
                        fontFamily: '"Geist Mono", ui-monospace, monospace',
                        fontSize: 11, color: isActive ? accent : 'var(--very-subtle)',
                        minWidth: 18
                      }}>{String(i + 1).padStart(2, '0')}</span>
                      <span>{s.title}</span>
                    </a>
                  </li>
                );
              })}
            </ol>
          </nav>

          {/* Sections */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 56 }}>
            {GUIDE_SECTIONS.map((s, i) => (
              <article key={s.id} id={s.id} style={{ scrollMarginTop: 96 }}>
                <div style={{
                  display: 'flex', alignItems: 'baseline', gap: 14, marginBottom: 16
                }}>
                  <span style={{
                    fontFamily: '"Geist Mono", ui-monospace, monospace',
                    fontSize: 13, fontWeight: 600, color: accent, letterSpacing: 0.6
                  }}>{String(i + 1).padStart(2, '0')}</span>
                  <h2 style={{
                    fontSize: 30, lineHeight: 1.15, letterSpacing: -0.8, fontWeight: 600,
                    margin: 0, color: 'var(--text)'
                  }}>{s.title}</h2>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                  {s.body.map((p, j) => (
                    <p key={j} style={{
                      fontSize: 16, lineHeight: 1.65, color: 'var(--muted)',
                      margin: 0, textWrap: 'pretty', maxWidth: 680
                    }}>{p}</p>
                  ))}
                </div>
              </article>
            ))}

            {/* End CTA */}
            <div style={{
              marginTop: 16, padding: '28px 30px',
              border: '1px solid var(--border)', borderRadius: 14,
              background: 'var(--surface)',
              display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 18,
              flexWrap: 'wrap'
            }}>
              <div>
                <div style={{ fontSize: 16, fontWeight: 600, color: 'var(--text)', letterSpacing: -0.2 }}>
                  Stuck on something?
                </div>
                <div style={{ fontSize: 13.5, color: 'var(--muted)', marginTop: 4 }}>
                  Email us — we get back to every resident within 48 hours.
                </div>
              </div>
              <a href="support.html" style={{
                padding: '11px 20px', fontSize: 14, fontWeight: 600, fontFamily: 'inherit',
                background: 'var(--btn-solid-bg)', color: 'var(--btn-solid-fg)',
                border: 'none', borderRadius: 9, cursor: 'pointer', letterSpacing: -0.1,
                textDecoration: 'none'
              }}>Contact support</a>
            </div>
          </div>
        </div>
      </section>

      <Footer accent={accent} />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<ResidentGuideApp />);
