// record-ui.jsx — shared atoms for PulseChart Record (self-contained;
// reuses window.PCT tokens). Includes a working signature canvas.

const RT = window.PCT;

function RIcon({ name, size = 16, color = 'currentColor', stroke = 1.7 }) {
  const p = { width:size, height:size, viewBox:'0 0 24 24', fill:'none', stroke:color, strokeWidth:stroke, strokeLinecap:'round', strokeLinejoin:'round' };
  switch (name) {
    case 'home': return <svg {...p}><path d="M3 11l9-8 9 8M5 9v12h14V9"/></svg>;
    case 'mic': return <svg {...p}><rect x="9" y="2" width="6" height="12" rx="3"/><path d="M5 10a7 7 0 0014 0M12 19v3"/></svg>;
    case 'doc': return <svg {...p}><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><path d="M14 2v6h6"/></svg>;
    case 'shield': return <svg {...p}><path d="M12 2l9 4v6c0 5-3.5 9.5-9 10-5.5-.5-9-5-9-10V6z"/></svg>;
    case 'discharge': return <svg {...p}><path d="M9 11l3 3L22 4M21 12v7a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h11"/></svg>;
    case 'right': return <svg {...p}><path d="M9 18l6-6-6-6"/></svg>;
    case 'left': return <svg {...p}><path d="M15 18l-6-6 6-6"/></svg>;
    case 'down': return <svg {...p}><path d="M6 9l6 6 6-6"/></svg>;
    case 'check': return <svg {...p}><path d="M5 13l4 4L19 7"/></svg>;
    case 'x': return <svg {...p}><path d="M18 6L6 18M6 6l12 12"/></svg>;
    case 'plus': return <svg {...p}><path d="M12 5v14M5 12h14"/></svg>;
    case 'edit': return <svg {...p}><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7M18.5 2.5a2.12 2.12 0 013 3L12 15l-4 1 1-4z"/></svg>;
    case 'sparkle': return <svg {...p}><path d="M12 3l1.5 6.5L20 11l-6.5 1.5L12 19l-1.5-6.5L4 11l6.5-1.5z"/></svg>;
    case 'alert': return <svg {...p}><path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/><path d="M12 9v4M12 17h.01"/></svg>;
    case 'info': return <svg {...p}><circle cx="12" cy="12" r="10"/><path d="M12 8v4M12 16h.01"/></svg>;
    case 'download': return <svg {...p}><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M7 10l5 5 5-5M12 15V3"/></svg>;
    case 'play': return <svg {...p}><path d="M5 3l14 9-14 9z"/></svg>;
    case 'stop': return <svg {...p}><rect x="5" y="5" width="14" height="14" rx="2"/></svg>;
    case 'user': return <svg {...p}><path d="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>;
    case 'users': return <svg {...p}><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 00-3-3.87M16 3.13a4 4 0 010 7.75"/></svg>;
    case 'baby': return <svg {...p}><circle cx="12" cy="9" r="5"/><path d="M9 9h.01M15 9h.01M9.5 13a3.5 3.5 0 005 0M5 21v-2a4 4 0 014-4h6a4 4 0 014 4v2"/></svg>;
    case 'bone': return <svg {...p}><path d="M17 10c1.1 0 2-.9 2-2a2 2 0 10-3.7-1H8.7A2 2 0 105 8c0 1.1.9 2 2 2 .5 2 .5 2 0 4a2 2 0 103.3 1h6a2 2 0 103.7-1c-.5-2-.5-2 0-4z"/></svg>;
    case 'pen': return <svg {...p}><path d="M12 19l7-7 3 3-7 7-3-3zM18 13l-1.5-1.5M2 22l5-1 9-9-4-4-9 9z"/></svg>;
    case 'refresh': return <svg {...p}><path d="M23 4v6h-6M1 20v-6h6M3.5 9a9 9 0 0114.85-3.36L23 10M1 14l4.65 4.36A9 9 0 0020.5 15"/></svg>;
    case 'link': return <svg {...p}><path d="M10 13a5 5 0 007.54.54l3-3a5 5 0 00-7.07-7.07l-1.72 1.71M14 11a5 5 0 00-7.54-.54l-3 3a5 5 0 007.07 7.07l1.71-1.71"/></svg>;
    case 'clock': return <svg {...p}><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg>;
    case 'whatsapp': return <svg width={size} height={size} viewBox="0 0 24 24" fill="#25D366"><path d="M20.5 3.5a10.5 10.5 0 00-16.5 13L3 21l4.6-1a10.5 10.5 0 0012.9-16.5z"/></svg>;
    case 'flag': return <svg {...p}><path d="M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1zM4 22V15"/></svg>;
    default: return null;
  }
}

function RBtn({ children, kind='ghost', size='md', onClick, icon, iconRight, full, disabled, type='button' }) {
  const sz = { sm:{h:30,px:12,fs:12.5}, md:{h:38,px:16,fs:13.5}, lg:{h:46,px:22,fs:15} }[size];
  const k = {
    primary:{bg:RT.c.accent,fg:'#fff',bd:RT.c.accent},
    dark:{bg:RT.c.text,fg:'#fff',bd:RT.c.text},
    ghost:{bg:RT.c.surface,fg:RT.c.text,bd:RT.c.border},
    soft:{bg:RT.c.surface2,fg:RT.c.text,bd:'transparent'},
    danger:{bg:RT.c.error,fg:'#fff',bd:RT.c.error},
    success:{bg:RT.c.success,fg:'#fff',bd:RT.c.success},
    brand:{bg:RT.c.brand,fg:'#fff',bd:RT.c.brand},
  }[kind];
  return (
    <button type={type} onClick={onClick} disabled={disabled} style={{
      display:'inline-flex', alignItems:'center', justifyContent:'center', gap:8,
      height:sz.h, padding:`0 ${sz.px}px`,
      background: disabled ? RT.c.surface2 : k.bg, color: disabled ? RT.c.textDim : k.fg,
      border:`1px solid ${disabled ? RT.c.border : k.bd}`, borderRadius:8,
      fontFamily:RT.f.sans, fontSize:sz.fs, fontWeight:500,
      cursor: disabled ? 'not-allowed' : 'pointer', whiteSpace:'nowrap', width: full ? '100%':'auto',
    }}>
      {icon && <RIcon name={icon} size={15}/>}{children}{iconRight && <RIcon name={iconRight} size={15}/>}
    </button>
  );
}

function RCard({ children, pad=22, style={}, onClick }) {
  return <div onClick={onClick} style={{ background:RT.c.surface, border:`1px solid ${RT.c.border}`, borderRadius:12, padding:pad, ...style }}>{children}</div>;
}

function RLabel({ children, right }) {
  return (
    <div style={{ display:'flex', alignItems:'baseline', justifyContent:'space-between', gap:12 }}>
      <div style={{ fontFamily:RT.f.mono, fontSize:10, fontWeight:600, letterSpacing:'.1em', textTransform:'uppercase', color:RT.c.textMuted }}>{children}</div>
      {right}
    </div>
  );
}

function RField({ label, hint, children, required }) {
  return (
    <div style={{ display:'flex', flexDirection:'column', gap:6 }}>
      <label style={{ fontFamily:RT.f.mono, fontSize:10, fontWeight:600, letterSpacing:'.08em', textTransform:'uppercase', color:RT.c.textMuted }}>
        {label}{required && <span style={{ color:RT.c.error, marginLeft:4 }}>*</span>}
      </label>
      {children}
      {hint && <div style={{ fontSize:11, color:RT.c.textDim, lineHeight:1.45 }}>{hint}</div>}
    </div>
  );
}

function RInput({ value, onChange, placeholder, mono, type='text' }) {
  return <input type={type} value={value ?? ''} onChange={e=>onChange&&onChange(e.target.value)} placeholder={placeholder}
    style={{ height:38, padding:'0 12px', background:RT.c.surface, border:`1px solid ${RT.c.border}`, borderRadius:8,
      fontFamily: mono?RT.f.mono:RT.f.sans, fontSize:13.5, color:RT.c.text, outline:'none' }}
    onFocus={e=>e.target.style.borderColor=RT.c.accent} onBlur={e=>e.target.style.borderColor=RT.c.border}/>;
}

function RTextarea({ value, onChange, placeholder, rows=3 }) {
  return <textarea value={value ?? ''} onChange={e=>onChange&&onChange(e.target.value)} placeholder={placeholder} rows={rows}
    style={{ padding:'10px 12px', background:RT.c.surface, border:`1px solid ${RT.c.border}`, borderRadius:8,
      fontFamily:RT.f.sans, fontSize:13.5, lineHeight:1.55, color:RT.c.text, outline:'none', resize:'vertical', width:'100%', boxSizing:'border-box' }}
    onFocus={e=>e.target.style.borderColor=RT.c.accent} onBlur={e=>e.target.style.borderColor=RT.c.border}/>;
}

function RSelect({ value, onChange, options, placeholder='Select…' }) {
  return (
    <div style={{ position:'relative' }}>
      <select value={value ?? ''} onChange={e=>onChange&&onChange(e.target.value)} style={{
        appearance:'none', WebkitAppearance:'none', width:'100%', height:38, padding:'0 32px 0 12px',
        background:RT.c.surface, border:`1px solid ${RT.c.border}`, borderRadius:8,
        fontFamily:RT.f.sans, fontSize:13.5, color:RT.c.text, outline:'none', cursor:'pointer' }}>
        {!value && <option value="">{placeholder}</option>}
        {options.map(o => <option key={typeof o==='object'?o.value:o} value={typeof o==='object'?o.value:o}>{typeof o==='object'?o.label:o}</option>)}
      </select>
      <div style={{ position:'absolute', right:10, top:'50%', transform:'translateY(-50%)', pointerEvents:'none' }}><RIcon name="down" size={12} color={RT.c.textMuted}/></div>
    </div>
  );
}

function RModal({ open, onClose, title, subtitle, width=640, children, footer }) {
  if (!open) return null;
  return ReactDOM.createPortal(
    <div onClick={onClose} style={{ position:'fixed', inset:0, zIndex:1000, background:'rgba(24,20,16,.42)', backdropFilter:'blur(6px)', display:'flex', alignItems:'center', justifyContent:'center', padding:24 }}>
      <div onClick={e=>e.stopPropagation()} style={{ background:RT.c.surface, borderRadius:14, width:'100%', maxWidth:width, maxHeight:'88vh', display:'flex', flexDirection:'column', boxShadow:'0 25px 60px -12px rgba(0,0,0,.25)', overflow:'hidden' }}>
        <div style={{ padding:'18px 24px', borderBottom:`1px solid ${RT.c.border}`, display:'flex', alignItems:'flex-start', justifyContent:'space-between', gap:14 }}>
          <div>
            <div style={{ fontSize:17, fontWeight:600, letterSpacing:'-.01em' }}>{title}</div>
            {subtitle && <div style={{ fontSize:12.5, color:RT.c.textMuted, marginTop:2 }}>{subtitle}</div>}
          </div>
          <button onClick={onClose} style={{ border:'none', background:'transparent', cursor:'pointer', width:30, height:30, borderRadius:7, display:'grid', placeItems:'center', color:RT.c.textMuted }}><RIcon name="x" size={17}/></button>
        </div>
        <div style={{ padding:24, overflow:'auto', flex:1 }}>{children}</div>
        {footer && <div style={{ padding:'14px 24px', borderTop:`1px solid ${RT.c.border}`, display:'flex', justifyContent:'flex-end', gap:8, background:RT.c.bg }}>{footer}</div>}
      </div>
    </div>, document.body);
}

// ── Badges ────────────────────────────────────────────────
function RUnverifiedBadge({ small }) {
  return (
    <span title="International benchmark — pending clinical validation" style={{
      display:'inline-flex', alignItems:'center', gap:5, padding: small?'1px 6px':'2px 8px', borderRadius:5,
      background:'#FEF3C7', color:'#92400E', fontSize: small?9.5:10.5, fontWeight:600,
      fontFamily:RT.f.mono, letterSpacing:'.03em', whiteSpace:'nowrap',
    }}>
      <RIcon name="alert" size={small?9:11} color="#B45309"/>UNVERIFIED
    </span>
  );
}
function RHmsBadge({ children, source }) {
  return (
    <span style={{ display:'inline-flex', alignItems:'center', gap:5, padding:'2px 8px', borderRadius:999, background:RT.c.brandSoft, color:RT.c.brand, fontSize:10.5, fontWeight:600, whiteSpace:'nowrap' }}>
      <svg width="10" height="10" viewBox="0 0 12 12" fill="currentColor"><rect x="1" y="2" width="10" height="8" rx="1.5"/></svg>
      {children || 'HMS'}{source && <span style={{ opacity:.6, fontFamily:RT.f.mono, fontSize:9.5 }}>· {source}</span>}
    </span>
  );
}
function RSpecChip({ specialty }) {
  const sp = window.PR.specialties[specialty];
  if (!sp) return null;
  return (
    <span style={{ display:'inline-flex', alignItems:'center', gap:6, padding:'3px 10px', borderRadius:999, background:sp.tint, color:sp.color, fontSize:11.5, fontWeight:600 }}>
      <RIcon name={specialty==='OBGYN'?'baby':'bone'} size={12} color={sp.color}/>{sp.short}
    </span>
  );
}

// ── Risk flag ─────────────────────────────────────────────
function RRiskFlag({ risk }) {
  const tones = {
    high:   { bg:RT.c.errorTint,   bar:RT.c.error,   fg:'#991B1B' },
    moderate:{bg:RT.c.warningTint, bar:RT.c.warning, fg:'#92400E' },
    low:    { bg:RT.c.successTint, bar:RT.c.success, fg:'#15803D' },
  }[risk.severity] || { bg:RT.c.surface2, bar:RT.c.textDim, fg:RT.c.text };
  return (
    <div style={{ background:tones.bg, borderLeft:`3px solid ${tones.bar}`, borderRadius:'0 8px 8px 0', padding:'10px 14px' }}>
      <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', gap:10 }}>
        <div style={{ display:'flex', alignItems:'center', gap:8 }}>
          <span style={{ fontSize:10, fontFamily:RT.f.mono, fontWeight:700, letterSpacing:'.06em', textTransform:'uppercase', color:tones.fg }}>{risk.severity}</span>
          <span style={{ fontSize:11, color:tones.fg, opacity:.7 }}>· {risk.category}</span>
        </div>
        {!risk.validated && <RUnverifiedBadge small/>}
      </div>
      <div style={{ fontSize:13, color:RT.c.text, marginTop:5, lineHeight:1.5, fontWeight:500 }}>{risk.description}</div>
      <div style={{ fontSize:11.5, color:RT.c.textMuted, marginTop:5 }}><strong style={{ color:tones.fg }}>Counsel:</strong> {risk.coverage}</div>
      <div style={{ fontSize:10, color:RT.c.textDim, marginTop:4, fontFamily:RT.f.mono }}>source: {risk.source}</div>
    </div>
  );
}

// ── Signature pad (real canvas) ──────────────────────────
function RSignaturePad({ onCapture, height=120 }) {
  const canvasRef = React.useRef(null);
  const drawing = React.useRef(false);
  const [hasInk, setHasInk] = React.useState(false);

  React.useEffect(() => {
    const c = canvasRef.current; if (!c) return;
    const ratio = window.devicePixelRatio || 1;
    c.width = c.offsetWidth * ratio; c.height = height * ratio;
    const ctx = c.getContext('2d'); ctx.scale(ratio, ratio);
    ctx.strokeStyle = '#18181A'; ctx.lineWidth = 2; ctx.lineCap = 'round'; ctx.lineJoin = 'round';
  }, [height]);

  const pos = (e) => {
    const c = canvasRef.current; const r = c.getBoundingClientRect();
    const t = e.touches ? e.touches[0] : e;
    return { x: t.clientX - r.left, y: t.clientY - r.top };
  };
  const start = (e) => { e.preventDefault(); drawing.current = true; const ctx = canvasRef.current.getContext('2d'); const {x,y}=pos(e); ctx.beginPath(); ctx.moveTo(x,y); };
  const move = (e) => { if (!drawing.current) return; e.preventDefault(); const ctx = canvasRef.current.getContext('2d'); const {x,y}=pos(e); ctx.lineTo(x,y); ctx.stroke(); setHasInk(true); };
  const end = () => { if (!drawing.current) return; drawing.current = false; if (onCapture) onCapture(canvasRef.current.toDataURL()); };
  const clear = () => { const c = canvasRef.current; c.getContext('2d').clearRect(0,0,c.width,c.height); setHasInk(false); if (onCapture) onCapture(null); };

  return (
    <div>
      <div style={{ position:'relative', border:`1.5px dashed ${RT.c.borderStrong}`, borderRadius:9, background:RT.c.surface2, overflow:'hidden' }}>
        <canvas ref={canvasRef} style={{ width:'100%', height, display:'block', cursor:'crosshair', touchAction:'none' }}
          onMouseDown={start} onMouseMove={move} onMouseUp={end} onMouseLeave={end}
          onTouchStart={start} onTouchMove={move} onTouchEnd={end}/>
        {!hasInk && <div style={{ position:'absolute', inset:0, display:'grid', placeItems:'center', pointerEvents:'none', color:RT.c.textDim, fontSize:12.5 }}>
          <span style={{ display:'flex', alignItems:'center', gap:7 }}><RIcon name="pen" size={14} color={RT.c.textDim}/>Sign here with mouse or finger</span>
        </div>}
      </div>
      <div style={{ display:'flex', justifyContent:'flex-end', marginTop:6 }}>
        <button onClick={clear} style={{ border:'none', background:'transparent', color:RT.c.textMuted, fontSize:11.5, cursor:'pointer', fontFamily:RT.f.sans }}>Clear</button>
      </div>
    </div>
  );
}

// ── Toast host ────────────────────────────────────────────
function RToastHost() {
  const store = useRStore();
  const t = store.state.toast;
  if (!t) return null;
  return ReactDOM.createPortal(
    <div style={{ position:'fixed', bottom:24, left:'50%', transform:'translateX(-50%)', zIndex:1100, animation:'pcToast .2s ease-out',
      background:RT.c.text, color:'#fff', padding:'12px 18px', borderRadius:10, boxShadow:'0 8px 24px rgba(0,0,0,.25)',
      display:'flex', alignItems:'center', gap:12, minWidth:280, maxWidth:480, fontSize:13 }}>
      {t.icon && <div style={{ width:28, height:28, borderRadius:7, background:'rgba(255,255,255,.12)', display:'grid', placeItems:'center', flexShrink:0 }}><RIcon name={t.icon} size={16} color="#fff"/></div>}
      <div style={{ flex:1, minWidth:0 }}>
        <div style={{ fontWeight:600 }}>{t.title}</div>
        {t.body && <div style={{ fontSize:11.5, opacity:.75, marginTop:2 }}>{t.body}</div>}
      </div>
    </div>, document.body);
}

Object.assign(window, {
  RIcon, RBtn, RCard, RLabel, RField, RInput, RTextarea, RSelect, RModal,
  RUnverifiedBadge, RHmsBadge, RSpecChip, RRiskFlag, RSignaturePad, RToastHost,
});
