/* Procedure library — a catalog page for common orthopedic procedures,
   loaded from the exported OrthoVaultOS procedure-name catalog (names +
   subspecialty only, no clinical content). The page reuses Nav and
   Footer from the marketing site, plus the same CSS-variable theme so
   dark/light + accent flow through. */

function useProcedureCatalog() {
  const [state, setState] = React.useState({ loading: true, error: null, subspecialties: [] });
  React.useEffect(() => {
    fetch('assets/data/procedure-catalog.json')
      .then((r) => { if (!r.ok) throw new Error('Failed to load catalog'); return r.json(); })
      .then((data) => setState({ loading: false, error: null, subspecialties: data.subspecialties || [] }))
      .catch((e) => setState({ loading: false, error: e.message, subspecialties: [] }));
  }, []);
  return state;
}

function ProcedureLibraryApp() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const accent = t.accent || '#b91c2c';
  const theme = t.theme || 'light';
  const isMobile = useIsMobile();
  const [filter, setFilter] = React.useState('All');
  const [query, setQuery] = React.useState('');
  const { loading, error, subspecialties } = useProcedureCatalog();

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

  const PROCEDURES = React.useMemo(() => subspecialties.flatMap((s) =>
    s.procedures.map((name) => ({ name, subspecialty: s.subspecialty }))
  ), [subspecialties]);

  const SUBSPECIALTIES = React.useMemo(() =>
    ['All', ...subspecialties.map((s) => s.subspecialty)],
  [subspecialties]);

  const filtered = PROCEDURES.filter((p) => {
    if (filter !== 'All' && p.subspecialty !== filter) return false;
    if (query.trim()) {
      const q = query.toLowerCase();
      if (!p.name.toLowerCase().includes(q) &&
          !p.subspecialty.toLowerCase().includes(q)) return false;
    }
    return true;
  });

  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' : '80px 28px 32px',
        position: 'relative',
        overflow: 'hidden'
      }}>
        <div aria-hidden="true" style={{
          position: 'absolute', inset: 0, pointerEvents: 'none',
          background: `radial-gradient(50% 70% at 80% 0%, ${accent}1a, transparent 60%)`,
        }}></div>
        <div style={{
          position: 'relative', maxWidth: 1200, margin: '0 auto',
          display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1.2fr 1fr', gap: isMobile ? 24 : 48, alignItems: 'end'
        }}>
          <div>
            <div style={{
              fontSize: 11.5, fontWeight: 600, color: accent, letterSpacing: 1.4,
              textTransform: 'uppercase', marginBottom: 14
            }}>Library</div>
            <h1 style={{
              fontSize: isMobile ? 32 : 64, lineHeight: 1.05, letterSpacing: isMobile ? -1 : -1.8, fontWeight: 600,
              margin: '0 0 18px', color: 'var(--text)', textWrap: 'balance'
            }}>
              Procedure{' '}
              <span style={{
                color: accent, fontWeight: 600,
                textTransform: 'uppercase', letterSpacing: -0.5
              }}>LIBRARY.</span>
            </h1>
            <p style={{
              fontSize: isMobile ? 15.5 : 17, lineHeight: 1.6, color: 'var(--muted)',
              margin: 0, maxWidth: 560, textWrap: 'pretty'
            }}>
              Starter templates for common orthopedic procedures. Each one becomes your own — fork it, mark up the steps, capture the pearls, attach the surgeon&rsquo;s preferences.
            </p>
          </div>
          <div style={{
            display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: isMobile ? 10 : 18,
            padding: isMobile ? '16px 16px' : '20px 22px',
            border: '1px solid var(--border)',
            borderRadius: 14,
            background: 'var(--surface)'
          }}>
            <Stat n={PROCEDURES.length.toString()} label="Procedures" />
            <Stat n={(SUBSPECIALTIES.length - 1).toString()} label="Subspecialties" />
            <Stat n="∞" label="Your forks" />
          </div>
        </div>
      </section>

      {/* Filters + search */}
      <section style={{ padding: isMobile ? '20px 20px 12px' : '24px 28px 16px', borderTop: '1px solid var(--border)', background: 'var(--surface-2)' }}>
        <div style={{ maxWidth: 1200, margin: '0 auto', display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
          <div style={{ position: 'relative', flex: isMobile ? '1 1 100%' : '0 0 auto', minWidth: isMobile ? 0 : 280 }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"
              style={{ position: 'absolute', left: 14, top: '50%', transform: 'translateY(-50%)', color: 'var(--subtle)' }}>
              <circle cx="11" cy="11" r="7"></circle>
              <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
            </svg>
            <input
              type="text"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              placeholder="Search procedures…"
              style={{
                padding: '10px 14px 10px 36px',
                fontSize: 14, fontFamily: 'inherit',
                background: 'var(--surface)',
                border: '1px solid var(--border-strong)',
                borderRadius: 9, color: 'var(--text)',
                width: isMobile ? '100%' : 280, boxSizing: 'border-box', outline: 'none'
              }}
            />
          </div>
          <a
            href="assets/data/procedure-catalog.json"
            download="OrthoVaultOS_Procedure_Catalog.json"
            style={{
              display: 'inline-flex', alignItems: 'center', gap: 7,
              padding: '9px 14px',
              fontSize: 13, fontWeight: 600, fontFamily: 'inherit',
              background: 'var(--surface)', color: 'var(--text)',
              border: '1px solid var(--border-strong)',
              borderRadius: 9, cursor: 'pointer', letterSpacing: -0.1,
              textDecoration: 'none', whiteSpace: 'nowrap'
            }}
          >
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
              <polyline points="7 10 12 15 17 10"></polyline>
              <line x1="12" y1="15" x2="12" y2="3"></line>
            </svg>
            Download catalog
          </a>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {SUBSPECIALTIES.map((s) => {
              const active = filter === s;
              return (
                <button key={s} onClick={() => setFilter(s)} style={{
                  padding: '8px 13px',
                  fontSize: 13, fontWeight: 500, fontFamily: 'inherit',
                  background: active ? 'var(--btn-solid-bg)' : 'var(--surface)',
                  color: active ? 'var(--btn-solid-fg)' : 'var(--muted)',
                  border: `1px solid ${active ? 'var(--btn-solid-bg)' : 'var(--border)'}`,
                  borderRadius: 100, cursor: 'pointer',
                  letterSpacing: -0.1
                }}>{s}</button>
              );
            })}
          </div>
        </div>
      </section>

      {/* Procedure grid */}
      <section style={{ padding: isMobile ? '24px 20px 56px' : '40px 28px 96px', background: 'var(--surface-2)' }}>
        <div style={{ maxWidth: 1200, margin: '0 auto' }}>
          {loading ? (
            <div style={{
              padding: 56, textAlign: 'center',
              border: '1px dashed var(--border-strong)',
              borderRadius: 14, background: 'var(--surface)',
              color: 'var(--subtle)', fontSize: 14
            }}>
              Loading procedures…
            </div>
          ) : error ? (
            <div style={{
              padding: 56, textAlign: 'center',
              border: '1px dashed var(--border-strong)',
              borderRadius: 14, background: 'var(--surface)',
              color: 'var(--subtle)', fontSize: 14
            }}>
              Couldn't load the procedure catalog right now.
            </div>
          ) : filtered.length === 0 ? (
            <div style={{
              padding: 56, textAlign: 'center',
              border: '1px dashed var(--border-strong)',
              borderRadius: 14, background: 'var(--surface)',
              color: 'var(--subtle)', fontSize: 14
            }}>
              No procedures match that filter yet.
            </div>
          ) : (
            <div style={{
              display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(240px, 1fr))', gap: 14
            }}>
              {filtered.map((p) => (
                <article key={`${p.subspecialty}::${p.name}`} style={{
                  background: 'var(--surface)',
                  border: '1px solid var(--border)',
                  borderRadius: 14,
                  padding: '18px 20px',
                  display: 'flex', flexDirection: 'column', gap: 10,
                  boxShadow: 'var(--shadow-card)',
                  transition: 'transform 0.15s ease, box-shadow 0.15s ease'
                }}
                onMouseEnter={(e) => { e.currentTarget.style.transform = 'translateY(-2px)'; e.currentTarget.style.boxShadow = 'var(--shadow-lg)'; }}
                onMouseLeave={(e) => { e.currentTarget.style.transform = ''; e.currentTarget.style.boxShadow = 'var(--shadow-card)'; }}
                >
                  <div style={{
                    fontSize: 10.5, fontWeight: 600, letterSpacing: 1, textTransform: 'uppercase',
                    color: accent, fontFamily: '"Geist Mono", ui-monospace, monospace'
                  }}>{p.subspecialty}</div>

                  <h3 style={{
                    fontSize: 16.5, fontWeight: 600, letterSpacing: -0.3,
                    margin: 0, color: 'var(--text)', textWrap: 'balance'
                  }}>{p.name}</h3>
                </article>
              ))}
            </div>
          )}

          <div style={{
            marginTop: 36, padding: '24px 28px',
            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: 14.5, fontWeight: 600, color: 'var(--text)', letterSpacing: -0.2 }}>
                Need a procedure that&rsquo;s not here?
              </div>
              <div style={{ fontSize: 13, color: 'var(--muted)', marginTop: 4 }}>
                Build it from scratch in the app — the procedure builder is specialty-agnostic.
              </div>
            </div>
            <a href="index.html" style={{
              padding: '10px 18px', fontSize: 13.5, 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'
            }}>Back to OrthoVaultOS</a>
          </div>
        </div>
      </section>

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

function Stat({ n, label }) {
  return (
    <div>
      <div style={{
        fontSize: 22, fontWeight: 600, letterSpacing: -0.6, color: 'var(--text)',
        fontFamily: '"Geist Mono", ui-monospace, monospace'
      }}>{n}</div>
      <div style={{ fontSize: 11.5, color: 'var(--subtle)', marginTop: 4 }}>{label}</div>
    </div>
  );
}

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