// Shared sketchy primitives + helpers used across all screens
const { useState, useEffect, useMemo, useRef } = React;

// Variation card frame
function Variation({ num, title, desc, children, w }) {
  return (
    <div className="var-card">
      <div className="var-label">
        <span className="num">{num}</span>
        <span className="t">{title}</span>
        <span className="desc">— {desc}</span>
      </div>
      <div className="sketch" style={w ? { maxWidth: w } : null}>
        <div className="sk-tb">
          <span className="dot"></span><span className="dot"></span><span className="dot"></span>
          <span className="url">khs-tracker.app/{title.toLowerCase().replace(/\s+/g,'-')}</span>
        </div>
        <div className="sk-body">{children}</div>
      </div>
    </div>
  );
}

// Sketchy nav rail (sidebar)
function Sidebar({ active = 'home', compact = false }) {
  const items = [
    ['home','Dashboard','◐'],
    ['part','Participants','◧'],
    ['auth','Authorizations','▤'],
    ['log','Service log','◔'],
    ['staff','Staff','◑'],
    ['rep','Reports','◬'],
    ['set','Settings','✦'],
  ];
  return (
    <div className="sk-box" style={{padding:compact?'8px 6px':'10px 8px',width:compact?56:148,minHeight:280,background:'var(--paper-2)'}}>
      {!compact && <div className="sk-cap" style={{padding:'2px 4px 6px'}}>menu</div>}
      <div className="sk-col" style={{gap:4}}>
        {items.map(([k,label,glyph]) => (
          <div key={k} style={{
            display:'flex',alignItems:'center',gap:8,
            padding:'5px 8px',borderRadius:6,
            border: active===k?'1.4px solid var(--ink)':'1.4px solid transparent',
            background: active===k?'var(--sage-tint)':'transparent',
            fontFamily:'Architects Daughter, cursive', fontSize:13
          }}>
            <span style={{width:14,textAlign:'center'}}>{glyph}</span>
            {!compact && <span>{label}</span>}
          </div>
        ))}
      </div>
    </div>
  );
}

// Top bar inside a sketch
function SketchTopBar({ title, search = true, right }) {
  return (
    <div style={{display:'flex',alignItems:'center',gap:10,marginBottom:12}}>
      <div className="hand-2" style={{fontSize:18}}>{title}</div>
      {search && <div className="sk-input mono" style={{flex:1,maxWidth:240,fontSize:11}}>⌕ search participants…</div>}
      <div style={{marginLeft:'auto',display:'flex',gap:6}}>
        {right || <>
          <span className="sk-pill">⎘ export</span>
          <span className="sk-btn primary">+ new</span>
        </>}
      </div>
    </div>
  );
}

// Status dot
function StatusDot({ s='ok', label }) {
  return <span className="sk-pill" style={{padding:'1px 8px'}}>
    <span className={`dot-st bg-${s}`}></span>{label}
  </span>;
}

// Mini horizontal usage bar with auth/used/remain split
function UsageBar({ used = 60, remain = 40, warn = false, height = 12 }) {
  const total = used + remain || 100;
  const pUsed = (used/total)*100;
  const fill = warn ? 'var(--r-orange)' : 'var(--sage)';
  return (
    <div style={{
      position:'relative',height,
      border:'1.3px solid var(--ink)',borderRadius:6,
      background:'#fff',overflow:'hidden'
    }}>
      <div style={{position:'absolute',inset:0,width:`${pUsed}%`,background:fill,
        backgroundImage:'repeating-linear-gradient(45deg,rgba(255,255,255,.15) 0 4px,transparent 4px 8px)'
      }}/>
      <div style={{position:'absolute',top:0,bottom:0,left:`${pUsed}%`,width:0,borderLeft:'1.4px dashed var(--ink)'}}/>
    </div>
  );
}

// SVG sketchy gauge (semicircle)
function Gauge({ pct = 70, status = 'ok', label }) {
  const r = 44;
  const cx = 60, cy = 56;
  const angle = Math.PI * (1 - pct/100);
  const x = cx + r * Math.cos(angle);
  const y = cy - r * Math.sin(angle);
  const color = `var(--r-${status})`;
  const dash = pct/100 * Math.PI * r;
  const arcLen = Math.PI * r;
  return (
    <svg width="120" height="70" viewBox="0 0 120 70">
      <path d={`M ${cx-r} ${cy} A ${r} ${r} 0 0 1 ${cx+r} ${cy}`}
            fill="none" stroke="var(--ink)" strokeWidth="2" strokeLinecap="round"/>
      <path d={`M ${cx-r} ${cy} A ${r} ${r} 0 0 1 ${cx+r} ${cy}`}
            fill="none" stroke={color} strokeWidth="6" strokeLinecap="round"
            strokeDasharray={`${dash} ${arcLen}`} opacity=".7"/>
      <line x1={cx} y1={cy} x2={x} y2={y} stroke="var(--ink)" strokeWidth="1.8" strokeLinecap="round"/>
      <circle cx={cx} cy={cy} r="3.5" fill="var(--paper)" stroke="var(--ink)" strokeWidth="1.5"/>
      <text x={cx} y={cy+18} textAnchor="middle" fontFamily="Architects Daughter" fontSize="12">{label || `${pct}%`}</text>
    </svg>
  );
}

// 12-month grid
function MonthGrid({ data, current = 4 /* index of current month, 0-11 */ }) {
  const months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  return (
    <div style={{display:'grid',gridTemplateColumns:'repeat(12,1fr)',gap:3}}>
      {months.map((m,i)=>{
        const v = data[i] ?? null;
        const past = i < current;
        const cur = i === current;
        const bg = v == null ? 'var(--paper-2)' :
                   v > 90 ? 'var(--r-orange)' :
                   v > 60 ? 'var(--sage)' :
                   v > 30 ? 'var(--sage-tint)' : 'var(--paper-2)';
        return (
          <div key={m} style={{
            border: cur?'1.6px solid var(--ink)':'1.2px solid var(--ink)',
            borderStyle: past?'solid':(v==null?'dashed':'solid'),
            borderRadius:5,padding:'4px 0 2px',textAlign:'center',
            background: bg,
            opacity: v==null?.55:1,
            fontFamily:'JetBrains Mono, monospace',fontSize:9
          }}>
            <div style={{fontFamily:'Architects Daughter',fontSize:10}}>{m}</div>
            <div style={{fontSize:10}}>{v ?? '—'}</div>
          </div>
        );
      })}
    </div>
  );
}

// Vertical sparkline bars
function Spark({ data, height = 32, color = 'sage' }) {
  const max = Math.max(...data, 1);
  return (
    <div style={{display:'flex',alignItems:'flex-end',gap:2,height}}>
      {data.map((v,i)=>(
        <span key={i} style={{
          display:'block',width:5,height:`${(v/max)*100}%`,minHeight:2,
          border:'1px solid var(--ink)',
          background: v/max>.85?'#f0c0b3':v/max>.6?'var(--sage)':'var(--sage-tint)',
          borderRadius:'2px 2px 0 0'
        }}/>
      ))}
    </div>
  );
}

// Circle initials avatar
function Avatar({ name = 'AP', tone = 'sage' }) {
  const bg = tone==='sage'?'var(--sage-tint)': tone==='warn'?'#f4d8b6':'#fff';
  return (
    <span style={{
      display:'inline-flex',alignItems:'center',justifyContent:'center',
      width:28,height:28,borderRadius:'50%',
      border:'1.4px solid var(--ink)',background:bg,
      fontFamily:'Architects Daughter',fontSize:11
    }}>{name}</span>
  );
}

// Sketchy text strokes (for placeholder copy)
function Strokes({ lines = 3, widths = ['100%','85%','60%'] }) {
  return (
    <div className="sk-col" style={{gap:6}}>
      {Array.from({length:lines}).map((_,i)=>(
        <div key={i} className="sk-line thin" style={{width: widths[i]||`${60+Math.random()*40}%`}}/>
      ))}
    </div>
  );
}

// Annotation note
function Note({ children, style }) {
  return <div className="sk-pill hand" style={{
    background:'#fffceb',borderColor:'var(--ink)',transform:'rotate(-1.5deg)',
    boxShadow:'2px 2px 0 var(--ink)',padding:'4px 10px',fontSize:16,...style
  }}>{children}</div>;
}

// Section header inside a sketch
function SkH({ children, kicker, right }) {
  return (
    <div style={{display:'flex',alignItems:'baseline',gap:10,marginBottom:8}}>
      {kicker && <span className="sk-cap">{kicker}</span>}
      <h3 className="sk-h">{children}</h3>
      {right && <span style={{marginLeft:'auto'}}>{right}</span>}
    </div>
  );
}

Object.assign(window, {
  Variation, Sidebar, SketchTopBar, StatusDot, UsageBar, Gauge,
  MonthGrid, Spark, Avatar, Strokes, Note, SkH
});
