// PerioSmart design tokens + shared atoms

const PS = {
  // Brand
  navy:    '#0A2540',
  navy90:  '#142D4A',
  navy70:  '#3F5573',
  navy40:  '#8A97AB',
  turq:    '#14B8B8',
  turq80:  '#3FC4C4',
  turqSoft:'#E6F7F7',
  turqInk: '#0A6B6B',

  // Neutrals — warm-cool clinical
  bg:      '#F6F7F9',
  surface: '#FFFFFF',
  line:    '#E5E8EE',
  line2:   '#EEF1F5',
  ink:     '#0A2540',
  ink70:   '#4A5567',
  ink50:   '#7A8597',
  ink30:   '#B4BBC7',

  // Severity scale (semantic — used on chart, diagnosis, indices)
  sev0:    '#16A34A', // healthy
  sev1:    '#84CC16', // mild
  sev2:    '#EAB308', // moderate
  sev3:    '#F97316', // severe
  sev4:    '#DC2626', // very severe

  // Surfaces
  cardShadow: '0 1px 0 rgba(10,37,64,0.04), 0 4px 16px rgba(10,37,64,0.04)',
  cardShadowLg: '0 1px 0 rgba(10,37,64,0.04), 0 12px 32px rgba(10,37,64,0.08)',

  // Type
  font: '"Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
  mono: '"IBM Plex Mono", "JetBrains Mono", ui-monospace, SFMono-Regular, monospace',
};

// Inject base styles once
if (typeof document !== 'undefined' && !document.getElementById('ps-base')) {
  const s = document.createElement('style');
  s.id = 'ps-base';
  s.textContent = `
    @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=IBM+Plex+Mono:wght@400;500;600&display=swap');
    .ps-root { font-family: ${PS.font}; color: ${PS.ink}; -webkit-font-smoothing: antialiased; letter-spacing: -0.005em; }
    .ps-root *, .ps-root *::before, .ps-root *::after { box-sizing: border-box; }
    .ps-mono { font-family: ${PS.mono}; font-feature-settings: "tnum" 1; }
    .ps-tnum { font-variant-numeric: tabular-nums; font-feature-settings: "tnum" 1; }
    .ps-scroll::-webkit-scrollbar { width: 8px; height: 8px; }
    .ps-scroll::-webkit-scrollbar-thumb { background: ${PS.line}; border-radius: 4px; }
    .ps-scroll::-webkit-scrollbar-track { background: transparent; }
  `;
  document.head.appendChild(s);
}

// ── Logo ───────────────────────────────────────────────────────────────
function PSLogo({ size = 28, color = PS.navy, accent = PS.turq, mono = false, withText = true }) {
  const c = mono ? color : color;
  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', gap: 10 }}>
      <svg width={size} height={size} viewBox="0 0 32 32">
        <circle cx="16" cy="16" r="15" fill="none" stroke={c} strokeWidth="1.5" />
        <circle cx="16" cy="16" r="15" fill="none" stroke={accent} strokeWidth="1.5"
          strokeDasharray="94" strokeDashoffset="70" transform="rotate(-90 16 16)" strokeLinecap="round" />
        <text x="16" y="20.5" textAnchor="middle"
          fontFamily={PS.font} fontWeight="700" fontSize="11" fill={c} letterSpacing="0.5">PS</text>
      </svg>
      {withText && (
        <div style={{ display: 'flex', flexDirection: 'column', lineHeight: 1 }}>
          <div style={{ fontWeight: 600, fontSize: size * 0.5, color: c, letterSpacing: '-0.01em' }}>PerioSmart</div>
        </div>
      )}
    </div>
  );
}

// ── Sidebar nav ────────────────────────────────────────────────────────
const NAV_ITEMS = [
  { id: 'home',    label: 'Tableau de bord', labelEn: 'Dashboard',     icon: 'home' },
  { id: 'pat',     label: 'Patients',         labelEn: 'Patients',      icon: 'users' },
  { id: 'diag',    label: 'Diagnostics',      labelEn: 'Diagnoses',     icon: 'chart' },
  { id: 'docs',    label: 'Documents',        labelEn: 'Documents',     icon: 'doc' },
  { id: 'edu',     label: 'Pédagogie patient',labelEn: 'Patient ed.',   icon: 'book' },
  { id: 'set',     label: 'Paramètres',       labelEn: 'Settings',      icon: 'cog' },
];

function NavIcon({ name, size = 18, color = 'currentColor' }) {
  const sw = 1.6;
  const props = { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: color, strokeWidth: sw, strokeLinecap: 'round', strokeLinejoin: 'round' };
  switch (name) {
    case 'home':  return <svg {...props}><path d="M3 11l9-7 9 7v9a2 2 0 0 1-2 2h-4v-7h-6v7H5a2 2 0 0 1-2-2z"/></svg>;
    case 'users': return <svg {...props}><circle cx="9" cy="8" r="3.2"/><path d="M3 20c.7-3.3 3-5 6-5s5.3 1.7 6 5"/><circle cx="17" cy="9" r="2.4"/><path d="M16 14c2.5.2 4.4 1.7 5 5"/></svg>;
    case 'chart': return <svg {...props}><path d="M4 20V10M10 20V4M16 20v-7M22 20H2"/></svg>;
    case 'doc':   return <svg {...props}><path d="M14 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"/><path d="M14 3v6h6M8 13h8M8 17h6"/></svg>;
    case 'book':  return <svg {...props}><path d="M4 4h7a3 3 0 0 1 3 3v13a2 2 0 0 0-2-2H4z"/><path d="M20 4h-7a3 3 0 0 0-3 3v13a2 2 0 0 1 2-2h8z"/></svg>;
    case 'cog':   return <svg {...props}><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 0 1-4 0v-.1A1.7 1.7 0 0 0 9 19.4a1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 0 1 0-4h.1A1.7 1.7 0 0 0 4.6 9a1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 0 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 0 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/></svg>;
    case 'plus':  return <svg {...props}><path d="M12 5v14M5 12h14"/></svg>;
    case 'search':return <svg {...props}><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>;
    case 'bell':  return <svg {...props}><path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/><path d="M10 21a2 2 0 0 0 4 0"/></svg>;
    case 'check': return <svg {...props}><path d="M20 6 9 17l-5-5"/></svg>;
    case 'arrow': return <svg {...props}><path d="M5 12h14M13 5l7 7-7 7"/></svg>;
    case 'down':  return <svg {...props}><path d="m6 9 6 6 6-6"/></svg>;
    case 'up':    return <svg {...props}><path d="m18 15-6-6-6 6"/></svg>;
    case 'info':  return <svg {...props}><circle cx="12" cy="12" r="9"/><path d="M12 16v-5M12 8h.01"/></svg>;
    case 'shield':return <svg {...props}><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>;
    case 'tooth': return <svg {...props}><path d="M7 3c-2 0-3.5 1.5-3.5 3.5 0 1.7.7 2.6 1 3.7.4 1.7-.5 3 .5 6.3.7 2.4 1.3 5.5 2.5 5.5 1.5 0 1-4 2.5-4s1 4 2.5 4c1.2 0 1.8-3.1 2.5-5.5 1-3.3.1-4.6.5-6.3.3-1.1 1-2 1-3.7C16.5 4.5 15 3 13 3c-1.5 0-2 1-3 1s-1.5-1-3-1z"/></svg>;
    case 'upload': return <svg {...props}><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M17 8l-5-5-5 5M12 3v12"/></svg>;
    case 'download': return <svg {...props}><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3"/></svg>;
    case 'print': return <svg {...props}><path d="M6 9V2h12v7M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/><path d="M6 14h12v8H6z"/></svg>;
    case 'sparkle': return <svg {...props}><path d="M12 3v4M12 17v4M3 12h4M17 12h4M5.6 5.6l2.8 2.8M15.6 15.6l2.8 2.8M5.6 18.4l2.8-2.8M15.6 8.4l2.8-2.8"/></svg>;
    case 'eye': return <svg {...props}><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="3"/></svg>;
    case 'flag': return <svg {...props}><path d="M4 22V4M4 16s2-2 5-2 5 2 8 2 3-2 3-2V4s-1 2-3 2-5-2-8-2-5 2-5 2"/></svg>;
    case 'lang': return <svg {...props}><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18"/></svg>;
    case 'more': return <svg {...props}><circle cx="5" cy="12" r="1"/><circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/></svg>;
    case 'x':    return <svg {...props}><path d="M18 6 6 18M6 6l12 12"/></svg>;
    case 'play': return <svg {...props}><path d="m6 4 14 8-14 8z" fill={color}/></svg>;
    default: return null;
  }
}

function Sidebar({ active = 'home', lang = 'fr', onNav }) {
  const navMap = { home: 'dashboard', pat: 'patients', diag: 'dashboard', docs: 'documents', edu: 'patientedu' };
  const enabled = new Set(['home', 'pat', 'diag', 'docs', 'edu']);
  return (
    <div style={{
      width: 220, background: PS.navy, color: '#fff', height: '100%',
      display: 'flex', flexDirection: 'column', flexShrink: 0,
    }}>
      <div style={{ padding: '20px 18px 22px', borderBottom: '1px solid rgba(255,255,255,0.08)' }}>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 10, cursor: 'pointer' }} onClick={() => onNav && onNav('dashboard')}>
          <svg width="28" height="28" viewBox="0 0 32 32">
            <circle cx="16" cy="16" r="15" fill="none" stroke="#fff" strokeWidth="1.5" />
            <circle cx="16" cy="16" r="15" fill="none" stroke={PS.turq} strokeWidth="1.5"
              strokeDasharray="94" strokeDashoffset="70" transform="rotate(-90 16 16)" strokeLinecap="round" />
            <text x="16" y="20.5" textAnchor="middle" fontWeight="700" fontSize="11" fill="#fff" letterSpacing="0.5">PS</text>
          </svg>
          <div style={{ fontWeight: 600, fontSize: 15, letterSpacing: '-0.01em' }}>PerioSmart</div>
        </div>
      </div>
      <div style={{ padding: '12px 8px', flex: 1, display: 'flex', flexDirection: 'column', gap: 2 }}>
        {NAV_ITEMS.map(it => {
          const on = it.id === active;
          const enabledItem = enabled.has(it.id);
          return (
            <div key={it.id} onClick={() => enabledItem && onNav && onNav(navMap[it.id])} style={{
              display: 'flex', alignItems: 'center', gap: 12,
              padding: '9px 12px', borderRadius: 8,
              background: on ? 'rgba(20,184,184,0.18)' : 'transparent',
              color: on ? '#fff' : enabledItem ? 'rgba(255,255,255,0.7)' : 'rgba(255,255,255,0.32)',
              borderLeft: on ? `2px solid ${PS.turq}` : '2px solid transparent',
              fontSize: 13, fontWeight: on ? 600 : 500, cursor: enabledItem ? 'pointer' : 'not-allowed',
            }}>
              <NavIcon name={it.icon} size={17} />
              <span>{lang === 'fr' ? it.label : it.labelEn}</span>
            </div>
          );
        })}
      </div>
      <div style={{ padding: 14, borderTop: '1px solid rgba(255,255,255,0.08)', display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ width: 32, height: 32, borderRadius: '50%', background: PS.turq, color: PS.navy,
          display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700, fontSize: 12 }}>DR</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 12, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>Dr. Romain</div>
          <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.55)' }}>Cabinet Lyon 6e</div>
        </div>
      </div>
    </div>
  );
}

// ── Topbar ─────────────────────────────────────────────────────────────
function TopBar({ title, sub, lang = 'fr', actions = null, breadcrumb = null, onLang, showBell = false }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: '18px 28px', borderBottom: `1px solid ${PS.line}`, background: '#fff',
      gap: 16,
    }}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 2, minWidth: 0 }}>
        {breadcrumb && (
          <div style={{ fontSize: 12, color: PS.ink50, display: 'flex', alignItems: 'center', gap: 6 }}>
            {breadcrumb}
          </div>
        )}
        <div style={{ fontSize: 20, fontWeight: 600, letterSpacing: '-0.015em' }}>{title}</div>
        {sub && <div style={{ fontSize: 13, color: PS.ink70 }}>{sub}</div>}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <LangToggle value={lang} onLang={onLang} />
        {showBell && (
          <div style={{ width: 36, height: 36, borderRadius: 8, border: `1px solid ${PS.line}`, display: 'flex', alignItems: 'center', justifyContent: 'center', color: PS.ink70 }}>
            <NavIcon name="bell" size={16} />
          </div>
        )}
        {actions}
      </div>
    </div>
  );
}

function DemoPill({ lang = 'fr', onRestart }) {
  if (!onRestart) return null;
  return (
    <div onClick={onRestart} title={lang === 'fr' ? 'Recommencer la démo' : 'Restart demo'} style={{
      position: 'fixed', bottom: 16, right: 16, zIndex: 1000,
      display: 'inline-flex', alignItems: 'center', gap: 9,
      padding: '0 16px', height: 38, borderRadius: 999,
      background: PS.navy, color: '#fff', cursor: 'pointer',
      fontSize: 12, fontWeight: 600, letterSpacing: '0.02em',
      boxShadow: '0 8px 24px rgba(10,37,64,0.28), 0 0 0 1px rgba(255,255,255,0.06) inset',
      fontFamily: PS.font, userSelect: 'none',
    }}>
      <span style={{ width: 7, height: 7, borderRadius: '50%', background: PS.turq, boxShadow: `0 0 0 3px rgba(20,184,184,0.3)` }} />
      {lang === 'fr' ? 'Démo · recommencer' : 'Demo · restart'}
    </div>
  );
}

function LangToggle({ value = 'fr', onLang }) {
  return (
    <div style={{ display: 'inline-flex', border: `1px solid ${PS.line}`, borderRadius: 8, overflow: 'hidden', fontSize: 11, fontWeight: 600, height: 36 }}>
      {['FR', 'EN'].map(l => {
        const on = value.toLowerCase() === l.toLowerCase();
        return (
          <div key={l} onClick={() => onLang && onLang(l.toLowerCase())} style={{
            padding: '0 12px', display: 'flex', alignItems: 'center',
            background: on ? PS.navy : '#fff', color: on ? '#fff' : PS.ink70,
            letterSpacing: '0.04em', cursor: 'pointer',
          }}>{l}</div>
        );
      })}
    </div>
  );
}

// ── Buttons ────────────────────────────────────────────────────────────
function Btn({ kind = 'primary', children, icon, iconRight, size = 'md', full = false, onClick }) {
  const heights = { sm: 30, md: 38, lg: 46 };
  const pads = { sm: 12, md: 16, lg: 20 };
  const fonts = { sm: 12, md: 13, lg: 14 };
  const styles = {
    primary:  { background: PS.navy, color: '#fff', border: `1px solid ${PS.navy}` },
    accent:   { background: PS.turq, color: '#fff', border: `1px solid ${PS.turq}` },
    secondary:{ background: '#fff', color: PS.ink, border: `1px solid ${PS.line}` },
    ghost:    { background: 'transparent', color: PS.ink70, border: '1px solid transparent' },
    danger:   { background: '#fff', color: PS.sev4, border: `1px solid ${PS.sev4}33` },
  }[kind];
  return (
    <button onClick={onClick} style={{
      ...styles, height: heights[size], padding: `0 ${pads[size]}px`,
      borderRadius: 8, fontSize: fonts[size], fontWeight: 600, cursor: 'pointer',
      display: 'inline-flex', alignItems: 'center', gap: 8, fontFamily: 'inherit',
      letterSpacing: '-0.005em', width: full ? '100%' : 'auto', justifyContent: 'center',
    }}>
      {icon && <NavIcon name={icon} size={size === 'lg' ? 18 : 15} />}
      {children}
      {iconRight && <NavIcon name={iconRight} size={size === 'lg' ? 18 : 15} />}
    </button>
  );
}

// ── Card ───────────────────────────────────────────────────────────────
function Card({ children, padding = 20, style = {} }) {
  return (
    <div style={{
      background: '#fff', borderRadius: 12, border: `1px solid ${PS.line}`,
      boxShadow: PS.cardShadow, padding, ...style,
    }}>
      {children}
    </div>
  );
}

// ── Badge ──────────────────────────────────────────────────────────────
function Badge({ children, kind = 'neutral', icon }) {
  const variants = {
    neutral: { bg: '#F3F5F8', fg: PS.ink70, bd: '#0000' },
    accent:  { bg: PS.turqSoft, fg: PS.turqInk, bd: '#0000' },
    navy:    { bg: 'rgba(10,37,64,0.06)', fg: PS.navy, bd: '#0000' },
    success: { bg: '#ECFDF5', fg: '#15803D', bd: '#0000' },
    warn:    { bg: '#FEF3C7', fg: '#92400E', bd: '#0000' },
    danger:  { bg: '#FEE2E2', fg: '#991B1B', bd: '#0000' },
    outline: { bg: '#fff', fg: PS.ink70, bd: PS.line },
  }[kind];
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 5,
      padding: '3px 8px', borderRadius: 999, fontSize: 11, fontWeight: 600,
      background: variants.bg, color: variants.fg, border: `1px solid ${variants.bd}`,
      letterSpacing: '0.01em', whiteSpace: 'nowrap',
    }}>
      {icon && <NavIcon name={icon} size={11} />}
      {children}
    </span>
  );
}

// ── Trust strip ────────────────────────────────────────────────────────
function TrustStrip({ compact = false }) {
  const items = [
    { l: 'CE', s: 'Medical device' },
    { l: 'HDS', s: 'Hébergeur Données Santé' },
    { l: 'RGPD', s: 'Conforme' },
  ];
  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', gap: compact ? 10 : 14 }}>
      {items.map(it => (
        <div key={it.l} style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
          <div style={{
            width: 22, height: 22, borderRadius: 4, border: `1px solid ${PS.line}`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 9, fontWeight: 700, color: PS.ink70, letterSpacing: '0.02em',
          }}>{it.l}</div>
          {!compact && <div style={{ fontSize: 10, color: PS.ink50 }}>{it.s}</div>}
        </div>
      ))}
    </div>
  );
}

// ── Wizard step indicator (used on patient diagnosis flow) ────────────
function StepIndicator({ steps, current }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 0 }}>
      {steps.map((s, i) => {
        const done = i < current;
        const active = i === current;
        return (
          <React.Fragment key={i}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, opacity: active || done ? 1 : 0.55 }}>
              <div style={{
                width: 22, height: 22, borderRadius: '50%',
                background: done ? PS.turq : active ? PS.navy : '#fff',
                color: done || active ? '#fff' : PS.ink50,
                border: `1px solid ${done ? PS.turq : active ? PS.navy : PS.line}`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 11, fontWeight: 700,
              }}>{done ? <NavIcon name="check" size={12}/> : i + 1}</div>
              <div style={{ fontSize: 12, fontWeight: active ? 600 : 500, color: active ? PS.ink : PS.ink70 }}>{s}</div>
            </div>
            {i < steps.length - 1 && (
              <div style={{ flex: 1, height: 1, background: i < current ? PS.turq : PS.line, margin: '0 14px', minWidth: 24 }} />
            )}
          </React.Fragment>
        );
      })}
    </div>
  );
}

// Stripe placeholder for imagery
function ImagePh({ width = '100%', height = 200, label = 'image', style = {} }) {
  return (
    <div style={{
      width, height, borderRadius: 8, border: `1px dashed ${PS.line}`,
      background: 'repeating-linear-gradient(135deg, #F6F7F9 0 8px, #FFFFFF 8px 16px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      color: PS.ink50, fontSize: 11, fontFamily: PS.mono, letterSpacing: '0.04em',
      ...style,
    }}>{label}</div>
  );
}

Object.assign(window, {
  PS, PSLogo, NavIcon, Sidebar, TopBar, LangToggle, DemoPill, Btn, Card, Badge,
  TrustStrip, StepIndicator, ImagePh, NAV_ITEMS,
});
