/* AppPreview — interactive mini-version of the OrthoVaultOS desktop app.
   Three columns: Specialty sidebar / Procedure list / Detail panel with surgeon prefs.
   Switching specialty / procedure / surgeon is wired live. */

const SPECIALTIES = [
  { id: 'knee', name: 'Knee', count: 14 },
  { id: 'hip', name: 'Hip', count: 11 },
  { id: 'spine', name: 'Spine', count: 9 },
  { id: 'shoulder', name: 'Shoulder', count: 8 },
  { id: 'sports', name: 'Sports', count: 12 },
  { id: 'trauma', name: 'Trauma', count: 16 },
  { id: 'foot', name: 'Foot & Ankle', count: 7 },
];

const PROCEDURES = {
  knee: [
    { code: '27447', name: 'Total Knee Arthroplasty', star: true },
    { code: '29881', name: 'Arthroscopic Meniscectomy', star: false },
    { code: '27486', name: 'Revision TKA, 1-component', star: false },
    { code: '29888', name: 'ACL Reconstruction', star: true },
    { code: '27438', name: 'Patellar Realignment', star: false },
  ],
  hip: [
    { code: '27130', name: 'Total Hip Arthroplasty', star: true },
    { code: '27125', name: 'Hemiarthroplasty, Hip', star: false },
    { code: '27132', name: 'Conversion to THA', star: false },
    { code: '27236', name: 'ORIF Femoral Neck Fx', star: false },
  ],
  spine: [
    { code: '22612', name: 'Lumbar Fusion, Posterior', star: false },
    { code: '63030', name: 'L4-L5 Microdiscectomy', star: true },
    { code: '22551', name: 'ACDF, C5-C6', star: false },
  ],
  shoulder: [
    { code: '23472', name: 'Reverse Shoulder Arthroplasty', star: false },
    { code: '29827', name: 'Arthroscopic RC Repair', star: true },
    { code: '23410', name: 'Open Bankart Repair', star: false },
  ],
  sports: [
    { code: '29888', name: 'ACL Reconstruction', star: true },
    { code: '29806', name: 'Arthroscopic SLAP Repair', star: false },
    { code: '27412', name: 'Cartilage Restoration', star: false },
  ],
  trauma: [
    { code: '27506', name: 'IM Nail, Femoral Shaft', star: false },
    { code: '27759', name: 'Tibial Nail', star: false },
    { code: '25607', name: 'ORIF Distal Radius', star: true },
  ],
  foot: [
    { code: '28296', name: 'Hallux Valgus Correction', star: false },
    { code: '28725', name: 'Subtalar Arthrodesis', star: false },
  ],
};

const SURGEONS = {
  '27447': [
    {
      id: 'patel',
      name: 'Dr. A. Patel',
      role: 'Attending · Joint Recon',
      prefs: {
        Position: 'Supine, leg holder, foot-of-bed bump',
        Approach: 'Medial parapatellar',
        Tourniquet: '325 mmHg · before incision',
        Gloves: 'Biogel 7.5 outer / 7.0 inner',
        Sutures: 'Stratafix 0 capsule · 2-0 sub-q · 3-0 Monocryl',
        Music: 'Coltrane radio, low',
        Pearls: 'Cement in 2 batches. Verify rotation against trans-epicondylar axis before final cuts.',
      },
      implants: ['Stryker Triathlon CR', 'Cemented tibial baseplate', 'Patellar resurface 32mm'],
    },
    {
      id: 'chen',
      name: 'Dr. M. Chen',
      role: 'Attending · Joint Recon',
      prefs: {
        Position: 'Supine, side-post, leg free',
        Approach: 'Subvastus',
        Tourniquet: 'No tourniquet · TXA 1g IV',
        Gloves: 'Ansell Encore 7.0',
        Sutures: 'Vicryl 1 capsule · 2-0 Monocryl · skin staples',
        Music: 'Surgeon picks per case',
        Pearls: 'Balance flexion gap first. Pie-crust MCL only if >3mm tight.',
      },
      implants: ['Zimmer Persona CR', 'Cementless tibia', 'No patellar resurface'],
    },
    {
      id: 'okafor',
      name: 'Dr. C. Okafor',
      role: 'Attending · Joint Recon',
      prefs: {
        Position: 'Supine, leg holder',
        Approach: 'Mid-vastus',
        Tourniquet: '300 mmHg · entire case',
        Gloves: 'Biogel 8.0',
        Sutures: 'Quill 1 · 2-0 Vicryl · Dermabond Prineo',
        Music: 'Classical, moderate volume',
        Pearls: 'Use spacer block in extension first. Document gap symmetry to 1mm.',
      },
      implants: ['Smith & Nephew Journey II', 'Cemented all', 'Patellar resurface'],
    },
  ],
  default: [
    {
      id: 'patel',
      name: 'Dr. A. Patel',
      role: 'Attending',
      prefs: {
        Position: 'Per technique guide',
        Approach: 'Standard',
        Tourniquet: 'As indicated',
        Gloves: 'Biogel 7.5',
        Sutures: 'Surgeon preference',
        Music: 'Coltrane radio',
        Pearls: 'See technique notes panel for details.',
      },
      implants: ['Surgeon-specific tray'],
    },
  ],
};

function StarIcon({ filled, size = 12 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill={filled ? 'currentColor' : 'none'} stroke="currentColor" strokeWidth="2" style={{ display: 'block' }}>
      <polygon points="12 2 15 9 22 9.3 17 14 18.5 21 12 17.5 5.5 21 7 14 2 9.3 9 9 12 2"></polygon>
    </svg>
  );
}

function ChevronIcon({ dir = 'down', size = 10 }) {
  const rot = dir === 'right' ? -90 : dir === 'up' ? 180 : 0;
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" style={{ display: 'block', transform: `rotate(${rot}deg)` }}>
      <polyline points="6 9 12 15 18 9"></polyline>
    </svg>
  );
}

function AppPreview({ accent = '#b91c2c', compact = false }) {
  const [specialty, setSpecialty] = React.useState('knee');
  const [procedureCode, setProcedureCode] = React.useState('27447');
  const [surgeonId, setSurgeonId] = React.useState('patel');
  const [tab, setTab] = React.useState('prefs');

  const procedures = PROCEDURES[specialty] || [];
  React.useEffect(() => {
    if (procedures.length && !procedures.find((p) => p.code === procedureCode)) {
      setProcedureCode(procedures[0].code);
    }
  }, [specialty]);

  const procedure = procedures.find((p) => p.code === procedureCode) || procedures[0];
  const surgeons = SURGEONS[procedureCode] || SURGEONS.default;
  const surgeon = surgeons.find((s) => s.id === surgeonId) || surgeons[0];
  React.useEffect(() => {
    if (!surgeons.find((s) => s.id === surgeonId)) setSurgeonId(surgeons[0].id);
  }, [procedureCode]);

  const ink = '#0e1525';
  const muted = '#5b6577';
  const subtle = '#8b95a5';
  const border = '#e7e8ec';
  const bgSubtle = '#f7f7f5';

  return (
    <div style={{
      width: '100%',
      maxWidth: compact ? 720 : 880,
      borderRadius: 14,
      overflow: 'hidden',
      background: '#ffffff',
      boxShadow: '0 1px 0 rgba(14,21,37,0.05), 0 30px 80px -30px rgba(14,21,37,0.35), 0 12px 28px -16px rgba(14,21,37,0.18)',
      border: `1px solid ${border}`,
      fontFamily: '"Geist", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
      color: ink,
      userSelect: 'none',
    }}>
      {/* Title bar */}
      <div style={{
        height: 36,
        display: 'flex',
        alignItems: 'center',
        padding: '0 14px',
        borderBottom: `1px solid ${border}`,
        background: 'linear-gradient(180deg, #fbfbfa 0%, #f5f5f3 100%)',
        gap: 14,
      }}>
        <div style={{ display: 'flex', gap: 6 }}>
          <span style={{ width: 11, height: 11, borderRadius: '50%', background: '#ff5f57' }}></span>
          <span style={{ width: 11, height: 11, borderRadius: '50%', background: '#febc2e' }}></span>
          <span style={{ width: 11, height: 11, borderRadius: '50%', background: '#28c840' }}></span>
        </div>
        <div style={{ flex: 1, textAlign: 'center', fontSize: 11.5, color: muted, letterSpacing: 0.2 }}>
          OrthoVaultOS — {procedure?.name}
        </div>
        <div style={{ width: 50 }}></div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: compact ? '150px 200px 1fr' : '170px 230px 1fr', minHeight: compact ? 380 : 460 }}>
        {/* Specialty sidebar */}
        <div style={{
          borderRight: `1px solid ${border}`,
          background: bgSubtle,
          padding: '14px 8px',
        }}>
          <div style={{ padding: '4px 10px 10px', fontSize: 10, fontWeight: 600, color: subtle, letterSpacing: 1.2, textTransform: 'uppercase' }}>
            Specialties
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
            {SPECIALTIES.map((s) => {
              const active = s.id === specialty;
              return (
                <button
                  key={s.id}
                  onClick={() => setSpecialty(s.id)}
                  style={{
                    border: 'none',
                    background: active ? '#ffffff' : 'transparent',
                    boxShadow: active ? '0 1px 0 rgba(14,21,37,0.04), 0 1px 2px rgba(14,21,37,0.06)' : 'none',
                    borderRadius: 6,
                    padding: '7px 10px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                    cursor: 'pointer',
                    fontSize: 12.5,
                    color: active ? ink : muted,
                    fontWeight: active ? 600 : 500,
                    fontFamily: 'inherit',
                    textAlign: 'left',
                  }}
                >
                  <span>{s.name}</span>
                  <span style={{ fontSize: 10.5, color: subtle, fontFamily: '"Geist Mono", ui-monospace, monospace' }}>{s.count}</span>
                </button>
              );
            })}
          </div>

          <div style={{ marginTop: 16, padding: '8px 10px', fontSize: 10, fontWeight: 600, color: subtle, letterSpacing: 1.2, textTransform: 'uppercase' }}>
            Library
          </div>
          <button style={{
            border: 'none', background: 'transparent', width: '100%', padding: '7px 10px', borderRadius: 6,
            display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer', fontSize: 12.5, color: muted, fontFamily: 'inherit',
          }}>
            <span style={{ color: accent }}><StarIcon filled size={12} /></span>
            <span>Favorites</span>
          </button>
          <button style={{
            border: 'none', background: 'transparent', width: '100%', padding: '7px 10px', borderRadius: 6,
            display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer', fontSize: 12.5, color: muted, fontFamily: 'inherit',
          }}>
            <span style={{ color: subtle }}>↻</span>
            <span>Recent</span>
          </button>
        </div>

        {/* Procedure list */}
        <div style={{ borderRight: `1px solid ${border}`, background: '#fcfcfb', display: 'flex', flexDirection: 'column' }}>
          <div style={{ padding: '12px 14px', borderBottom: `1px solid ${border}` }}>
            <div style={{ fontSize: 11, color: subtle, letterSpacing: 0.4, textTransform: 'uppercase', fontWeight: 600 }}>
              {SPECIALTIES.find((s) => s.id === specialty)?.name} procedures
            </div>
            <div style={{ marginTop: 8, position: 'relative' }}>
              <input
                placeholder="Search…"
                readOnly
                style={{
                  width: '100%', padding: '6px 10px', fontSize: 12, border: `1px solid ${border}`, borderRadius: 6,
                  background: '#fff', color: muted, fontFamily: 'inherit', outline: 'none',
                }}
              />
            </div>
          </div>
          <div style={{ overflow: 'auto', flex: 1 }}>
            {procedures.map((p) => {
              const active = p.code === procedureCode;
              return (
                <button
                  key={p.code}
                  onClick={() => setProcedureCode(p.code)}
                  style={{
                    width: '100%', textAlign: 'left', border: 'none', background: active ? '#fff' : 'transparent',
                    borderLeft: active ? `2px solid ${accent}` : '2px solid transparent',
                    padding: '10px 14px',
                    cursor: 'pointer', display: 'flex', flexDirection: 'column', gap: 3,
                    borderBottom: `1px solid ${border}`, fontFamily: 'inherit',
                  }}
                >
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                    <span style={{ fontSize: 10.5, color: subtle, fontFamily: '"Geist Mono", ui-monospace, monospace', letterSpacing: 0.3 }}>{p.code}</span>
                    {p.star && <span style={{ color: accent }}><StarIcon filled size={11} /></span>}
                  </div>
                  <span style={{ fontSize: 12.5, fontWeight: active ? 600 : 500, color: ink, lineHeight: 1.3 }}>{p.name}</span>
                </button>
              );
            })}
          </div>
        </div>

        {/* Detail panel */}
        <div style={{ display: 'flex', flexDirection: 'column', minWidth: 0 }}>
          {/* Procedure header */}
          <div style={{ padding: '14px 18px 0', borderBottom: `1px solid ${border}` }}>
            <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12 }}>
              <div style={{ minWidth: 0 }}>
                <div style={{ fontSize: 10.5, color: subtle, fontFamily: '"Geist Mono", ui-monospace, monospace', letterSpacing: 0.4 }}>
                  CPT {procedure?.code} · {SPECIALTIES.find((s) => s.id === specialty)?.name}
                </div>
                <div style={{ fontSize: compact ? 17 : 19, fontWeight: 600, marginTop: 3, letterSpacing: -0.3, lineHeight: 1.2 }}>
                  {procedure?.name}
                </div>
              </div>
              <button style={{
                border: `1px solid ${border}`, background: '#fff', borderRadius: 6,
                padding: '5px 9px', fontSize: 11.5, color: muted, display: 'flex', alignItems: 'center', gap: 5,
                cursor: 'pointer', fontFamily: 'inherit', flexShrink: 0,
              }}>
                <StarIcon filled={procedure?.star} size={10} />
                <span>{procedure?.star ? 'Starred' : 'Star'}</span>
              </button>
            </div>

            {/* Surgeon tabs */}
            <div style={{ marginTop: 12, display: 'flex', gap: 4, alignItems: 'flex-end' }}>
              <div style={{ fontSize: 10, color: subtle, marginRight: 6, marginBottom: 8, fontWeight: 600, letterSpacing: 1, textTransform: 'uppercase' }}>
                Surgeon
              </div>
              {surgeons.map((s) => {
                const active = s.id === surgeonId;
                return (
                  <button
                    key={s.id}
                    onClick={() => setSurgeonId(s.id)}
                    style={{
                      border: 'none', background: 'transparent', padding: '6px 10px 7px',
                      borderBottom: active ? `2px solid ${accent}` : '2px solid transparent',
                      marginBottom: -1,
                      fontSize: 12, fontWeight: active ? 600 : 500,
                      color: active ? ink : muted, cursor: 'pointer', fontFamily: 'inherit',
                    }}
                  >
                    {s.name}
                  </button>
                );
              })}
            </div>
          </div>

          {/* Section tabs */}
          <div style={{ display: 'flex', gap: 0, padding: '0 18px', borderBottom: `1px solid ${border}`, background: '#fcfcfb' }}>
            {[
              { id: 'prefs', label: 'Preferences' },
              { id: 'steps', label: 'Steps' },
              { id: 'technique', label: 'Technique' },
              { id: 'evidence', label: 'Evidence' },
              { id: 'implants', label: 'Implants' },
            ].map((t) => {
              const active = t.id === tab;
              return (
                <button
                  key={t.id}
                  onClick={() => setTab(t.id)}
                  style={{
                    border: 'none', background: 'transparent',
                    padding: '9px 0', marginRight: 16,
                    fontSize: 11.5, fontWeight: active ? 600 : 500,
                    color: active ? ink : muted, cursor: 'pointer',
                    borderBottom: active ? `2px solid ${ink}` : '2px solid transparent',
                    marginBottom: -1, fontFamily: 'inherit',
                  }}
                >
                  {t.label}
                </button>
              );
            })}
          </div>

          {/* Panel body */}
          <div style={{ padding: '14px 18px', flex: 1, overflow: 'auto' }}>
            {tab === 'prefs' && (
              <div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
                  <div style={{
                    width: 28, height: 28, borderRadius: 6, background: accent, color: '#fff',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontFamily: '"Geist Mono", ui-monospace, monospace', fontSize: 11, fontWeight: 600, letterSpacing: 0.3,
                  }}>
                    {surgeon.name.split(' ').slice(-1)[0].slice(0, 2).toUpperCase()}
                  </div>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 600 }}>{surgeon.name}</div>
                    <div style={{ fontSize: 11, color: muted }}>{surgeon.role}</div>
                  </div>
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: compact ? '1fr' : '1fr 1fr', gap: 0, border: `1px solid ${border}`, borderRadius: 8, overflow: 'hidden' }}>
                  {Object.entries(surgeon.prefs).map(([k, v], i) => (
                    <div key={k} style={{
                      padding: '10px 12px',
                      borderBottom: i < Object.keys(surgeon.prefs).length - (compact ? 1 : 2) ? `1px solid ${border}` : 'none',
                      borderRight: !compact && i % 2 === 0 ? `1px solid ${border}` : 'none',
                      background: '#fff',
                    }}>
                      <div style={{ fontSize: 10, color: subtle, fontWeight: 600, letterSpacing: 0.6, textTransform: 'uppercase', marginBottom: 3 }}>{k}</div>
                      <div style={{ fontSize: 12, color: ink, lineHeight: 1.45 }}>{v}</div>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {tab === 'steps' && (
              <ol style={{ margin: 0, padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 8 }}>
                {[
                  'Patient positioning & verification of operative side',
                  'Tourniquet placement; pre-incision prophylactic antibiotics',
                  'Skin incision, soft-tissue dissection, capsulotomy',
                  'Exposure of joint, removal of osteophytes',
                  'Distal femur and proximal tibia cuts using surgeon-specific guides',
                  'Trial components, gap and rotation assessment',
                  'Cementation and final implant placement',
                  'Closure in layers per surgeon preference',
                ].map((step, i) => (
                  <li key={i} style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
                    <span style={{
                      flexShrink: 0, width: 20, height: 20, borderRadius: 4, background: bgSubtle,
                      color: muted, fontFamily: '"Geist Mono", ui-monospace, monospace', fontSize: 10.5,
                      display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 600,
                    }}>{i + 1}</span>
                    <span style={{ fontSize: 12.5, color: ink, lineHeight: 1.5 }}>{step}</span>
                  </li>
                ))}
              </ol>
            )}

            {tab === 'technique' && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {[
                  { name: 'Patel_TKA_technique_v3.pdf', size: '2.4 MB', kind: 'PDF' },
                  { name: 'medial_release_pearls.docx', size: '184 KB', kind: 'DOC' },
                  { name: 'rotational_landmarks.png', size: '1.1 MB', kind: 'IMG' },
                ].map((f) => (
                  <div key={f.name} style={{
                    display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px',
                    border: `1px solid ${border}`, borderRadius: 8, background: '#fff',
                  }}>
                    <div style={{
                      width: 28, height: 28, borderRadius: 4, background: bgSubtle, color: muted,
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      fontFamily: '"Geist Mono", ui-monospace, monospace', fontSize: 9.5, fontWeight: 600,
                    }}>{f.kind}</div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 12.5, color: ink, fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{f.name}</div>
                      <div style={{ fontSize: 11, color: subtle, fontFamily: '"Geist Mono", ui-monospace, monospace' }}>{f.size}</div>
                    </div>
                    <span style={{ color: subtle, fontSize: 12 }}>↗</span>
                  </div>
                ))}
              </div>
            )}

            {tab === 'evidence' && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {[
                  { title: 'Long-term outcomes of cemented vs cementless TKA', journal: 'JBJS · 2024', cite: '142 citations' },
                  { title: 'Trans-epicondylar axis for rotational alignment', journal: 'CORR · 2022', cite: '88 citations' },
                  { title: 'TXA in arthroplasty: dosing meta-analysis', journal: 'Bone & Joint J · 2023', cite: '67 citations' },
                ].map((p) => (
                  <div key={p.title} style={{ padding: '10px 12px', border: `1px solid ${border}`, borderRadius: 8, background: '#fff' }}>
                    <div style={{ fontSize: 12.5, color: ink, fontWeight: 500, lineHeight: 1.35 }}>{p.title}</div>
                    <div style={{ fontSize: 11, color: subtle, marginTop: 3, fontFamily: '"Geist Mono", ui-monospace, monospace', letterSpacing: 0.2 }}>{p.journal} · {p.cite}</div>
                  </div>
                ))}
              </div>
            )}

            {tab === 'implants' && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                {surgeon.implants.map((imp) => (
                  <div key={imp} style={{
                    padding: '8px 12px', border: `1px solid ${border}`, borderRadius: 6, background: '#fff',
                    fontSize: 12.5, color: ink, display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                  }}>
                    <span>{imp}</span>
                    <span style={{ fontSize: 10.5, color: subtle, fontFamily: '"Geist Mono", ui-monospace, monospace' }}>in tray</span>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Status bar */}
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '6px 14px', borderTop: `1px solid ${border}`, background: bgSubtle,
            fontSize: 10.5, color: subtle, fontFamily: '"Geist Mono", ui-monospace, monospace', letterSpacing: 0.3,
          }}>
            <span>● Ready</span>
            <span>De-identified · No patient data</span>
            <span>3 surgeons · 14 procedures</span>
          </div>
        </div>
      </div>
    </div>
  );
}

window.AppPreview = AppPreview;
