// ComplianceDashboard.jsx
// Role-specific compliance checklists: Office Manager, Assistant, Hygienist.
// Includes: daily/weekly/monthly/annual cadences, completion tracking,
// performance scoring integration, CE suggestions, OSHA + infection control.
// All state in localStorage — no PHI, no backend required for MVP.
// Exported: window.ComplianceDashboard

const { useState: useCDS, useEffect: useCDE, useMemo: useCDM, useCallback: useCDC } = React;

function Fi({ name, size = 20, color = 'currentColor', style }) {
  return window.FlatIcon
    ? React.createElement(window.FlatIcon, { name, size, color, style })
    : null;
}

const ROLE_TAB_ICONS = { office: 'building', assistant: 'tooth', hygienist: 'broom' };
const ROLE_TAB_LABELS = { office: 'Office Mgr', assistant: 'Assistant', hygienist: 'Hygienist' };
const MAIN_TABS = [
  ['checklist', 'clipboard', 'Checklists'],
  ['score', 'chart', 'Performance Score'],
  ['ce', 'graduation', 'CE Tracker'],
];

// ── Date helpers ──────────────────────────────────────────────────────────────
const today     = () => new Date().toISOString().split('T')[0];
const thisWeek  = () => { const d=new Date(); return `${d.getFullYear()}-W${String(Math.ceil((d.getDate()+new Date(d.getFullYear(),d.getMonth(),1).getDay())/7)).padStart(2,'0')}`; };
const thisMonth = () => new Date().toISOString().slice(0,7);
const thisYear  = () => String(new Date().getFullYear());

function periodKey(cadence) {
  if (cadence==='daily')   return today();
  if (cadence==='weekly')  return thisWeek();
  if (cadence==='monthly') return thisMonth();
  if (cadence==='annual')  return thisYear();
  return today();
}

// ── Compliance task definitions ───────────────────────────────────────────────
const TASKS = {
  office: [
    // DAILY
    { id:'o_d1',  role:'office', cadence:'daily',   category:'Safety',       title:'Verify emergency kit is present and accessible',         ref:'OSHA 29 CFR 1910.151' },
    { id:'o_d2',  role:'office', cadence:'daily',   category:'Compliance',   title:'Review HIPAA access log for any anomalies',              ref:'HIPAA §164.312(b)' },
    { id:'o_d3',  role:'office', cadence:'daily',   category:'Financial',    title:'Reconcile end-of-day collections with schedule',         ref:'Internal Policy' },
    { id:'o_d4',  role:'office', cadence:'daily',   category:'Operations',   title:'Confirm next-day schedule has no insurance gaps',         ref:'Best Practice' },
    { id:'o_d5',  role:'office', cadence:'daily',   category:'Compliance',   title:'Verify all clinical notes are signed and locked',        ref:'State Board' },
    // WEEKLY
    { id:'o_w1',  role:'office', cadence:'weekly',  category:'HR',           title:'Review time-off requests and schedule coverage',         ref:'Internal Policy' },
    { id:'o_w2',  role:'office', cadence:'weekly',  category:'Compliance',   title:'Audit treatment plans with pending pre-authorization',   ref:'ADA Guidelines' },
    { id:'o_w3',  role:'office', cadence:'weekly',  category:'Financial',    title:'Review outstanding insurance claims (>30 days)',          ref:'Best Practice' },
    { id:'o_w4',  role:'office', cadence:'weekly',  category:'Safety',       title:'Check AED battery and defibrillator pads expiration',    ref:'OSHA / AHA' },
    { id:'o_w5',  role:'office', cadence:'weekly',  category:'Operations',   title:'Review patient satisfaction scores (VPS queue)',          ref:'TheDentist.ai VPS' },
    // MONTHLY
    { id:'o_m1',  role:'office', cadence:'monthly', category:'Compliance',   title:'OSHA required monthly team safety meeting — document it', ref:'OSHA 1910.1030' },
    { id:'o_m2',  role:'office', cadence:'monthly', category:'Financial',    title:'Review accounts receivable aging report',                 ref:'Best Practice' },
    { id:'o_m3',  role:'office', cadence:'monthly', category:'Compliance',   title:'Audit PHI access logs and security incident reports',     ref:'HIPAA §164.308' },
    { id:'o_m4',  role:'office', cadence:'monthly', category:'HR',           title:'Conduct 1:1 check-ins with all clinical staff',          ref:'Best Practice' },
    { id:'o_m5',  role:'office', cadence:'monthly', category:'Safety',       title:'Inspect and document autoclave spore test results',      ref:'CDC / State Board' },
    // ANNUAL
    { id:'o_a1',  role:'office', cadence:'annual',  category:'Compliance',   title:'Complete OSHA annual training — all staff',              ref:'OSHA 1910.1030(g)(1)' },
    { id:'o_a2',  role:'office', cadence:'annual',  category:'Compliance',   title:'Update HIPAA Notice of Privacy Practices',               ref:'HIPAA §164.520' },
    { id:'o_a3',  role:'office', cadence:'annual',  category:'Compliance',   title:'Conduct HIPAA risk assessment and document findings',    ref:'HIPAA §164.308(a)(1)' },
    { id:'o_a4',  role:'office', cadence:'annual',  category:'HR',           title:'Complete performance reviews for all team members',      ref:'Best Practice' },
    { id:'o_a5',  role:'office', cadence:'annual',  category:'Safety',       title:'Test and document emergency action plan drill',          ref:'OSHA 1910.38' },
    { id:'o_a6',  role:'office', cadence:'annual',  category:'Financial',    title:'Review fee schedule against FAIR Health benchmarks',     ref:'ADA / FAIR Health' },
  ],
  assistant: [
    // DAILY
    { id:'a_d1',  role:'assistant', cadence:'daily',   category:'Infection Control', title:'Don appropriate PPE before first patient (mask, gloves, eye protection)',      ref:'CDC/OSHA' },
    { id:'a_d2',  role:'assistant', cadence:'daily',   category:'Infection Control', title:'Verify sterilization indicator on every cassette before use',                  ref:'OSAP / CDC' },
    { id:'a_d3',  role:'assistant', cadence:'daily',   category:'Infection Control', title:'Disinfect all surfaces between patients (barriers changed)',                    ref:'CDC 2016 Guidelines' },
    { id:'a_d4',  role:'assistant', cadence:'daily',   category:'Infection Control', title:'Run and log daily autoclave cycle (biological indicator on day 1 of week)',     ref:'OSAP Checklist' },
    { id:'a_d5',  role:'assistant', cadence:'daily',   category:'Operations',        title:'Set up trays per scheduled procedure — verify completeness before seating',     ref:'Best Practice' },
    { id:'a_d6',  role:'assistant', cadence:'daily',   category:'Compliance',        title:'Document all materials used in chart for accurate billing',                     ref:'ADA Coding' },
    { id:'a_d7',  role:'assistant', cadence:'daily',   category:'Safety',            title:'Check nitrous oxide lines and e-cylinder gauge before start of day',            ref:'NFPA / ADA' },
    // WEEKLY
    { id:'a_w1',  role:'assistant', cadence:'weekly',  category:'Infection Control', title:'Clean and test ultrasonic cleaner effectiveness',                              ref:'OSAP' },
    { id:'a_w2',  role:'assistant', cadence:'weekly',  category:'Infection Control', title:'Inspect and replace evacuation system trap',                                   ref:'Manufacturer / OSHA' },
    { id:'a_w3',  role:'assistant', cadence:'weekly',  category:'Safety',            title:'Inspect sharps containers — replace when ¾ full',                              ref:'OSHA 1910.1030' },
    { id:'a_w4',  role:'assistant', cadence:'weekly',  category:'Operations',        title:'Audit supply levels; reorder consumables that are low',                         ref:'Best Practice' },
    { id:'a_w5',  role:'assistant', cadence:'weekly',  category:'Compliance',        title:'Review any updated chairside protocols or technique changes from provider',     ref:'Office Policy' },
    // MONTHLY
    { id:'a_m1',  role:'assistant', cadence:'monthly', category:'Infection Control', title:'Biological spore test for all sterilizers — log results',                      ref:'CDC / State Board' },
    { id:'a_m2',  role:'assistant', cadence:'monthly', category:'Safety',            title:'Inspect and document radiation badge (dosimetry) if applicable',                ref:'NRC / State Reg' },
    { id:'a_m3',  role:'assistant', cadence:'monthly', category:'Infection Control', title:'Flush waterlines 30+ seconds at start of shift; check DUWLs',                  ref:'CDC Guidelines' },
    { id:'a_m4',  role:'assistant', cadence:'monthly', category:'Operations',        title:'Review coding accuracy for assisted procedures last month',                     ref:'ADA/ABA Compliance' },
    // ANNUAL
    { id:'a_a1',  role:'assistant', cadence:'annual',  category:'Compliance',        title:'Complete OSHA Bloodborne Pathogens training — retain certificate',              ref:'OSHA 1910.1030' },
    { id:'a_a2',  role:'assistant', cadence:'annual',  category:'Compliance',        title:'Hepatitis B vaccination series check / titer verification',                    ref:'OSHA 1910.1030' },
    { id:'a_a3',  role:'assistant', cadence:'annual',  category:'CE',                title:'Complete 8 CE hours for DA license renewal (CA requirement)',                   ref:'CDPH / DA Council' },
    { id:'a_a4',  role:'assistant', cadence:'annual',  category:'Safety',            title:'Radiation safety review — technique, collimation, patient shielding',           ref:'State Dental Board' },
  ],
  hygienist: [
    // DAILY
    { id:'h_d1',  role:'hygienist', cadence:'daily',   category:'Infection Control', title:'Verify high-level disinfection of reusable instruments',                       ref:'CDC 2016 Guidelines' },
    { id:'h_d2',  role:'hygienist', cadence:'daily',   category:'Clinical',          title:'Review medical history updates for every patient before seating',               ref:'ADA / Risk Mgmt' },
    { id:'h_d3',  role:'hygienist', cadence:'daily',   category:'Clinical',          title:'Take and document blood pressure for applicable patients',                      ref:'AHA / JADA' },
    { id:'h_d4',  role:'hygienist', cadence:'daily',   category:'Clinical',          title:'Perform and document full periodontal charting per schedule',                   ref:'AAP Guidelines' },
    { id:'h_d5',  role:'hygienist', cadence:'daily',   category:'Compliance',        title:'Complete and lock clinical notes before end of shift',                         ref:'State Board' },
    { id:'h_d6',  role:'hygienist', cadence:'daily',   category:'Infection Control', title:'Flush handpiece waterlines 30 sec between patients; 2 min at start of day',    ref:'CDC DUWLs 2016' },
    { id:'h_d7',  role:'hygienist', cadence:'daily',   category:'Clinical',          title:'Provide and document oral hygiene instructions for each patient',               ref:'Best Practice' },
    // WEEKLY
    { id:'h_w1',  role:'hygienist', cadence:'weekly',  category:'Clinical',          title:'Review radiograph audit — ensure proper technique and documentation',           ref:'State Board / FDA' },
    { id:'h_w2',  role:'hygienist', cadence:'weekly',  category:'Compliance',        title:'Review recall effectiveness — patients 6+ months overdue for hygiene visit',    ref:'Best Practice' },
    { id:'h_w3',  role:'hygienist', cadence:'weekly',  category:'Operations',        title:'Verify supply of anesthetic, topical, and fluoride varnish',                   ref:'Best Practice' },
    // MONTHLY
    { id:'h_m1',  role:'hygienist', cadence:'monthly', category:'Clinical',          title:'Self-audit periodontal charting accuracy vs. radiograph correlation',           ref:'AAP' },
    { id:'h_m2',  role:'hygienist', cadence:'monthly', category:'Clinical',          title:'Review case acceptance rate for periodontal treatment recommendations',          ref:'VPS / Best Practice' },
    { id:'h_m3',  role:'hygienist', cadence:'monthly', category:'Compliance',        title:'Document patient refusals of recommended treatment (signed)',                   ref:'Risk Management' },
    { id:'h_m4',  role:'hygienist', cadence:'monthly', category:'Infection Control', title:'Maintain DUWL shock treatment log (e.g., Sterilex, Citrisil)',                  ref:'CDC / Manufacturer' },
    // ANNUAL
    { id:'h_a1',  role:'hygienist', cadence:'annual',  category:'CE',                title:'Complete 25 CE hours for CA RDH license renewal (2-year cycle, ~12/yr)',        ref:'CDPH RDH Requirements' },
    { id:'h_a2',  role:'hygienist', cadence:'annual',  category:'CE',                title:'Maintain current CPR/AED certification (BLS level)',                            ref:'AHA / OSHA' },
    { id:'h_a3',  role:'hygienist', cadence:'annual',  category:'Compliance',        title:'Complete OSHA Bloodborne Pathogens refresher training',                         ref:'OSHA 1910.1030' },
    { id:'h_a4',  role:'hygienist', cadence:'annual',  category:'Clinical',          title:'Complete local anesthesia administration log review (if permitted in state)',    ref:'State Board' },
    { id:'h_a5',  role:'hygienist', cadence:'annual',  category:'CE',                title:'Attend one AAP / ADHA chapter event for clinical updates',                      ref:'Professional Development' },
  ],
};

// ── CE suggestions per role ───────────────────────────────────────────────────
const CE_SUGGESTIONS = {
  assistant: [
    { title:'Infection Control Excellence for Dental Assistants',  hours:4,  provider:'OSAP',         link:'https://osap.org' },
    { title:'Dental Radiography Technique & Safety Update',        hours:4,  provider:'ADAA',         link:'https://adaausa.org' },
    { title:'Chairside Ergonomics and Musculoskeletal Injury Prev',hours:2,  provider:'ADA CE',       link:'https://cdeworld.com' },
    { title:'Digital Impressions & CAD/CAM Chairside Workflows',   hours:4,  provider:'Practice Helper', link:'https://dentistapprentice.com' },
    { title:'Expanded Functions for Dental Assistants (CA)',        hours:8,  provider:'CDPH-approved',link:'https://cdph.ca.gov' },
  ],
  hygienist: [
    { title:'Periodontal Disease Management — AAP 2018 Classification Update', hours:3, provider:'AAP', link:'https://perio.org' },
    { title:'Motivational Interviewing for Oral Health Behavior Change',        hours:2, provider:'ADHA',link:'https://adha.org' },
    { title:'Medical Emergency Management for the Dental Office',               hours:3, provider:'ADA CE',link:'https://cdeworld.com' },
    { title:'Locally Administered Antibiotics in Periodontal Therapy',          hours:2, provider:'ADHA',link:'https://adha.org' },
    { title:'Pediatric Oral Health — Recognition and Prevention',               hours:3, provider:'AAPD',link:'https://aapd.org' },
    { title:'Full-Arch Implant Maintenance Protocols for Hygienists',           hours:2, provider:'Practice Helper',link:'https://dentistapprentice.com' },
  ],
  office: [
    { title:'HIPAA Compliance for Dental Offices 2026',           hours:2,  provider:'ADA CE',        link:'https://cdeworld.com' },
    { title:'Dental Insurance Billing & Coding Accuracy',         hours:4,  provider:'AADOM',         link:'https://aadom.com' },
    { title:'Treatment Plan Presentation & Case Acceptance',      hours:3,  provider:'Practice Helper', link:'https://dentistapprentice.com' },
    { title:'OSHA Compliance Update for Dental Practices',        hours:2,  provider:'OSHA Education',link:'https://osha.gov' },
    { title:'Leading a High-Performance Dental Team',             hours:4,  provider:'AADOM',         link:'https://aadom.com' },
  ],
};

// ── VPS axis impact mapping ───────────────────────────────────────────────────
const VPS_IMPACT = {
  'Infection Control': 'Anxious-Friendly · Patient Favorite',
  'Clinical':          'Continuity Champion · Patient Favorite',
  'Safety':            'Anxious-Friendly',
  'Compliance':        'All axes — compliance gaps hurt VPS globally',
  'Operations':        'Budget-Conscious · Family-Friendly',
  'CE':                'Continuity Champion · Clinical Excellence',
  'HR':                'Continuity Champion · Team stability',
  'Financial':         'Budget-Conscious',
};

// ── Colors ────────────────────────────────────────────────────────────────────
const CAT_CLR = {
  'Infection Control':'#27c1a3','Clinical':'#4da3ff','Safety':'#e8b339',
  'Compliance':'#a78bfa','Operations':'#fb923c','CE':'#f472b6',
  'HR':'#6ee7b7','Financial':'#fbbf24',
};
const ROLE_CLR = { office:'#27c1a3', assistant:'#4da3ff', hygienist:'#f472b6' };
const CADENCE_LABEL = { daily:'Daily', weekly:'Weekly', monthly:'Monthly', annual:'Annual' };

// ─────────────────────────────────────────────────────────────────────────────
// MAIN COMPONENT
// ─────────────────────────────────────────────────────────────────────────────
function ComplianceDashboard({ role: defaultRole = 'office' }) {
  const [role, setRole] = useCDS(defaultRole);
  const [cadence, setCadence] = useCDS('daily');
  const [checks, setChecks] = useCDS(() => {
    try { return JSON.parse(localStorage.getItem('compliance_checks') || '{}'); }
    catch { return {}; }
  });
  const [tab, setTab] = useCDS('checklist'); // 'checklist' | 'score' | 'ce'
  const [notes, setNotes] = useCDS(() => {
    try { return JSON.parse(localStorage.getItem('compliance_notes') || '{}'); }
    catch { return {}; }
  });

  const saveChecks = (next) => {
    setChecks(next);
    localStorage.setItem('compliance_checks', JSON.stringify(next));
  };
  const saveNotes = (next) => {
    setNotes(next);
    localStorage.setItem('compliance_notes', JSON.stringify(next));
  };

  const getKey = (taskId, cadence) => `${taskId}__${periodKey(cadence)}`;

  const toggle = (task) => {
    const k = getKey(task.id, task.cadence);
    const next = { ...checks, [k]: !checks[k] };
    saveChecks(next);
  };

  const setNote = (taskId, val) => {
    const next = { ...notes, [taskId]: val };
    saveNotes(next);
  };

  // ── Filtered tasks ──
  const filteredTasks = useCDM(() =>
    TASKS[role].filter(t => t.cadence === cadence),
    [role, cadence]
  );

  // ── Completion stats ──
  const stats = useCDM(() => {
    const roleAll = TASKS[role];
    const cadences = ['daily','weekly','monthly','annual'];
    return cadences.reduce((acc, cad) => {
      const tasks = roleAll.filter(t => t.cadence === cad);
      const done  = tasks.filter(t => checks[getKey(t.id, cad)]).length;
      acc[cad] = { total: tasks.length, done };
      return acc;
    }, {});
  }, [role, checks]);

  // ── Score (0–100) — simple weighted completion ──
  const complianceScore = useCDM(() => {
    const weights = { annual:4, monthly:3, weekly:2, daily:1 };
    let totalW = 0, doneW = 0;
    Object.entries(stats).forEach(([cad, {total, done}]) => {
      const w = weights[cad];
      totalW += total * w;
      doneW  += done  * w;
    });
    return totalW === 0 ? 0 : Math.round((doneW / totalW) * 100);
  }, [stats]);

  const scoreColor = complianceScore >= 80 ? '#3fb96b' : complianceScore >= 50 ? '#e8b339' : '#e5654f';

  const roleColor  = ROLE_CLR[role] || '#27c1a3';

  // ── Category breakdown ──
  const catBreakdown = useCDM(() => {
    const cats = {};
    TASKS[role].forEach(t => {
      if (!cats[t.category]) cats[t.category] = { total:0, done:0 };
      cats[t.category].total++;
      if (checks[getKey(t.id, t.cadence)]) cats[t.category].done++;
    });
    return cats;
  }, [role, checks]);

  return (
    <div style={{fontFamily:"system-ui,'Segoe UI',sans-serif",color:'#e6edf3',minHeight:'100vh',background:'#0b1116'}}>
      {/* Header */}
      <div style={{background:'#121a22',borderBottom:'1px solid #1f2b36',padding:'16px 20px'}}>
        <div style={{display:'flex',alignItems:'center',gap:12,flexWrap:'wrap'}}>
          <Fi name="circleCheck" size={20} color="#3fb96b"/>
          <h2 style={{margin:0,fontSize:18,fontWeight:800}}>Compliance Dashboard</h2>
          {/* Role selector */}
          <div style={{display:'flex',gap:4,marginLeft:'auto',background:'#0f161d',padding:3,borderRadius:8,border:'1px solid #1f2b36'}}>
            {['office','assistant','hygienist'].map(r => (
              <button key={r} onClick={() => setRole(r)}
                style={{padding:'5px 12px',borderRadius:6,border:'none',cursor:'pointer',fontSize:11,fontWeight:700,textTransform:'capitalize',
                  background: role===r ? roleColor : 'transparent',
                  color: role===r ? '#0b1116' : '#8b9aa7'}}>
                <span style={{display:'inline-flex',alignItems:'center',gap:5}}>
                  <Fi name={ROLE_TAB_ICONS[r]} size={12} color={role===r ? '#0b1116' : '#8b9aa7'}/>
                  {ROLE_TAB_LABELS[r]}
                </span>
              </button>
            ))}
          </div>
        </div>

        {/* Tab bar */}
        <div style={{display:'flex',gap:4,marginTop:14,borderBottom:'1px solid #1f2b36'}}>
          {MAIN_TABS.map(([k, icon, label]) => (
            <button key={k} onClick={() => setTab(k)}
              style={{padding:'8px 16px',background:'transparent',border:'none',borderBottom: tab===k ? `2px solid ${roleColor}` : '2px solid transparent',
                cursor:'pointer',fontSize:12,fontWeight:700,color: tab===k ? '#e6edf3' : '#8b9aa7',display:'inline-flex',alignItems:'center',gap:6}}>
              <Fi name={icon} size={14} color={tab===k ? '#e6edf3' : '#8b9aa7'}/> {label}
            </button>
          ))}
        </div>
      </div>

      <div style={{padding:'16px 20px',maxWidth:900,margin:'0 auto'}}>

        {/* ── CHECKLISTS TAB ── */}
        {tab === 'checklist' && (
          <div>
            {/* Cadence selector + progress strip */}
            <div style={{display:'flex',gap:8,marginBottom:16,flexWrap:'wrap',alignItems:'center'}}>
              {['daily','weekly','monthly','annual'].map(c => {
                const s = stats[c];
                const pct = s.total ? Math.round((s.done/s.total)*100) : 0;
                return (
                  <button key={c} onClick={() => setCadence(c)}
                    style={{padding:'6px 14px',borderRadius:8,border:`1px solid ${cadence===c ? roleColor : '#1f2b36'}`,
                      cursor:'pointer',background: cadence===c ? '#0f161d' : 'transparent',
                      color: cadence===c ? '#e6edf3' : '#8b9aa7',fontSize:12,fontWeight:700,position:'relative'}}>
                    {CADENCE_LABEL[c]}
                    <span style={{marginLeft:6,fontSize:10,color: pct===100?'#3fb96b':pct>0?'#e8b339':'#8b9aa7',fontWeight:700}}>
                      {s.done}/{s.total}
                    </span>
                  </button>
                );
              })}
              <span style={{marginLeft:'auto',fontSize:11,color:'#8b9aa7'}}>
                Period: <strong style={{color:'#e6edf3'}}>{periodKey(cadence)}</strong>
              </span>
            </div>

            {/* Task cards */}
            <div style={{display:'flex',flexDirection:'column',gap:8}}>
              {filteredTasks.map(task => {
                const k    = getKey(task.id, task.cadence);
                const done = !!checks[k];
                const clr  = CAT_CLR[task.category] || '#8b9aa7';
                return (
                  <div key={task.id}
                    style={{background: done ? '#0a1a0f' : '#0f161d',
                      border:`1px solid ${done ? '#1a4228' : '#1f2b36'}`,
                      borderLeft:`3px solid ${done ? '#3fb96b' : clr}`,
                      borderRadius:8,padding:'10px 14px',transition:'all 0.2s'}}>
                    <div style={{display:'flex',alignItems:'flex-start',gap:10}}>
                      <input type="checkbox" checked={done} onChange={() => toggle(task)}
                        style={{marginTop:2,width:16,height:16,accentColor:roleColor,cursor:'pointer',flexShrink:0}}/>
                      <div style={{flex:1}}>
                        <div style={{fontSize:13,color: done?'#8b9aa7':'#e6edf3',fontWeight:600,
                          textDecoration: done?'line-through':'none'}}>
                          {task.title}
                        </div>
                        <div style={{display:'flex',gap:8,marginTop:4,flexWrap:'wrap'}}>
                          <span style={{fontSize:10,color:clr,fontWeight:600,padding:'2px 6px',background:'#1f2b36',borderRadius:4}}>
                            {task.category}
                          </span>
                          <span style={{fontSize:10,color:'#8b9aa7'}}>Ref: {task.ref}</span>
                          {VPS_IMPACT[task.category] && (
                            <span style={{fontSize:10,color:'#4da3ff'}}>→ VPS: {VPS_IMPACT[task.category]}</span>
                          )}
                        </div>
                        {/* Note field */}
                        <div style={{marginTop:6}}>
                          <input
                            placeholder="Add note (optional)…"
                            value={notes[task.id] || ''}
                            onChange={e => setNote(task.id, e.target.value)}
                            style={{width:'100%',background:'#0b1116',border:'1px solid #1f2b36',borderRadius:6,
                              color:'#8b9aa7',fontSize:11,padding:'4px 8px',outline:'none',boxSizing:'border-box'}}/>
                        </div>
                      </div>
                    </div>
                  </div>
                );
              })}
              {filteredTasks.length === 0 && (
                <div style={{textAlign:'center',color:'#8b9aa7',padding:32,fontSize:13}}>
                  No {cadence} tasks for {role} role.
                </div>
              )}
            </div>
          </div>
        )}

        {/* ── PERFORMANCE SCORE TAB ── */}
        {tab === 'score' && (
          <div>
            {/* Overall score ring */}
            <div style={{display:'flex',gap:20,alignItems:'center',background:'#0f161d',border:'1px solid #1f2b36',borderRadius:12,padding:'20px 24px',marginBottom:20}}>
              <svg viewBox="0 0 120 120" width={100} height={100}>
                <circle cx={60} cy={60} r={50} fill="none" stroke="#1f2b36" strokeWidth={10}/>
                <circle cx={60} cy={60} r={50} fill="none" stroke={scoreColor} strokeWidth={10}
                  strokeDasharray={`${2*Math.PI*50}`}
                  strokeDashoffset={`${2*Math.PI*50*(1-complianceScore/100)}`}
                  strokeLinecap="round" transform="rotate(-90 60 60)" style={{transition:'stroke-dashoffset 0.6s'}}/>
                <text x={60} y={65} textAnchor="middle" fontSize={22} fontWeight={800} fill={scoreColor}>{complianceScore}</text>
              </svg>
              <div>
                <div style={{fontSize:16,fontWeight:800,color:'#e6edf3',marginBottom:4}}>
                  Compliance Score — {role.charAt(0).toUpperCase()+role.slice(1)}
                </div>
                <div style={{fontSize:13,color:'#8b9aa7',marginBottom:8,display:'flex',alignItems:'center',gap:6}}>
                  {complianceScore >= 80
                    ? <><Fi name="circleCheck" size={14} color="#3fb96b"/> Excellent compliance posture</>
                    : complianceScore >= 50
                      ? <><Fi name="alert" size={14} color="#e8b339"/> Some items overdue — review below</>
                      : <><Fi name="dot" size={14} color="#e5654f"/> Critical gaps — act today</>}
                </div>
                <div style={{fontSize:11,color:'#8b9aa7',lineHeight:1.6}}>
                  Score weights: Annual (4×) · Monthly (3×) · Weekly (2×) · Daily (1×)<br/>
                  Connected to VPS — compliance gaps affect recognition scores.
                </div>
              </div>
            </div>

            {/* Cadence breakdown */}
            <div style={{display:'grid',gridTemplateColumns:'repeat(2,1fr)',gap:12,marginBottom:20}}>
              {Object.entries(stats).map(([cad, {total, done}]) => {
                const pct = total ? Math.round((done/total)*100) : 0;
                const clr = pct===100?'#3fb96b':pct>=50?'#e8b339':'#e5654f';
                return (
                  <div key={cad} style={{background:'#0f161d',border:'1px solid #1f2b36',borderRadius:10,padding:'12px 16px'}}>
                    <div style={{display:'flex',justifyContent:'space-between',marginBottom:6}}>
                      <span style={{fontSize:12,fontWeight:700,textTransform:'capitalize',color:'#e6edf3'}}>{cad}</span>
                      <span style={{fontSize:12,fontWeight:700,color:clr}}>{done}/{total}</span>
                    </div>
                    <div style={{height:5,background:'#1f2b36',borderRadius:3}}>
                      <div style={{height:5,width:`${pct}%`,background:clr,borderRadius:3,transition:'width 0.4s'}}/>
                    </div>
                  </div>
                );
              })}
            </div>

            {/* Category breakdown */}
            <div style={{background:'#0f161d',border:'1px solid #1f2b36',borderRadius:12,padding:'14px 16px',marginBottom:20}}>
              <div style={{fontSize:13,fontWeight:700,color:'#e6edf3',marginBottom:12}}>By Category</div>
              <div style={{display:'flex',flexDirection:'column',gap:8}}>
                {Object.entries(catBreakdown).map(([cat, {total, done}]) => {
                  const pct = total ? Math.round((done/total)*100) : 0;
                  const clr = CAT_CLR[cat] || '#8b9aa7';
                  return (
                    <div key={cat}>
                      <div style={{display:'flex',justifyContent:'space-between',marginBottom:3}}>
                        <span style={{fontSize:12,color:clr,fontWeight:600}}>{cat}</span>
                        <span style={{fontSize:11,color:'#8b9aa7'}}>{done}/{total} · {pct}%</span>
                      </div>
                      <div style={{height:4,background:'#1f2b36',borderRadius:3}}>
                        <div style={{height:4,width:`${pct}%`,background:clr,borderRadius:3}}/>
                      </div>
                      {pct < 60 && (
                        <div style={{fontSize:10,color:'#e8b339',marginTop:2,display:'flex',alignItems:'center',gap:4}}>
                          <Fi name="alert" size={10} color="#e8b339"/> VPS impact: {VPS_IMPACT[cat]}
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            </div>

            {/* Flagged items */}
            <div style={{background:'#1a0e00',border:'1px solid #4a2800',borderRadius:12,padding:'14px 16px'}}>
              <div style={{fontSize:13,fontWeight:700,color:'#e8b339',marginBottom:10,display:'flex',alignItems:'center',gap:6}}>
                <Fi name="alert" size={14} color="#e8b339"/> Overdue / Incomplete Items
              </div>
              {Object.entries(stats).some(([c,s]) => s.done < s.total) ? (
                Object.entries({ annual:TASKS[role].filter(t=>t.cadence==='annual'), monthly:TASKS[role].filter(t=>t.cadence==='monthly') })
                  .flatMap(([cad, tasks]) =>
                    tasks.filter(t => !checks[getKey(t.id,t.cadence)])
                      .map(t => (
                        <div key={t.id} style={{fontSize:12,color:'#b3822f',borderBottom:'1px solid #3a2200',padding:'6px 0',display:'flex',gap:8}}>
                          <span style={{color:CAT_CLR[t.category]||'#8b9aa7',fontWeight:700}}>[{t.cadence.toUpperCase()}]</span>
                          <span>{t.title}</span>
                        </div>
                      ))
                  )
              ) : (
                <div style={{fontSize:12,color:'#3fb96b',display:'flex',alignItems:'center',gap:4}}>
                  <Fi name="check" size={12} color="#3fb96b"/> All high-weight items complete for this period.
                </div>
              )}
            </div>
          </div>
        )}

        {/* ── CE TRACKER TAB ── */}
        {tab === 'ce' && (
          <div>
            <p style={{fontSize:13,color:'#8b9aa7',marginBottom:18,lineHeight:1.6}}>
              Continuing Education suggestions tailored to your role. Track completed courses and hours toward license renewal requirements.
            </p>

            {/* CA license CE requirement reminder */}
            <div style={{background:'#0f1a26',border:'1px solid #1f2b36',borderRadius:10,padding:'12px 16px',marginBottom:18}}>
              <div style={{fontSize:12,fontWeight:700,color:'#4da3ff',marginBottom:6}}>
                <span style={{display:'inline-flex',alignItems:'center',gap:6}}>
                  <Fi name="clipboard" size={14} color="#e6edf3"/>
                  CA License CE Requirements — {role === 'assistant' ? 'Dental Assistant' : role === 'hygienist' ? 'Registered Dental Hygienist' : 'Office Manager'}
                </span>
              </div>
              {role === 'assistant' && <div style={{fontSize:12,color:'#8b9aa7'}}>8 CE hours per year (CDPH-approved). Infection control required every 2 years.</div>}
              {role === 'hygienist' && <div style={{fontSize:12,color:'#8b9aa7'}}>25 CE hours per 2-year renewal cycle (~12-13/year). CPR required. 2 hours on PA Board-approved topics.</div>}
              {role === 'office' && <div style={{fontSize:12,color:'#8b9aa7'}}>No state CE requirement for office managers, but AADOM recommends 15–20 hours/year for professional designation.</div>}
            </div>

            {/* Course cards */}
            <div style={{display:'flex',flexDirection:'column',gap:10}}>
              {CE_SUGGESTIONS[role].map((c, i) => {
                const doneKey = `ce_done_${role}_${i}`;
                const done = !!checks[doneKey];
                return (
                  <div key={i} style={{background: done ? '#0a1a0f' : '#0f161d',
                    border:`1px solid ${done?'#1a4228':'#1f2b36'}`,borderRadius:10,padding:'12px 16px',
                    display:'flex',gap:12,alignItems:'flex-start'}}>
                    <input type="checkbox" checked={done}
                      onChange={() => saveChecks({...checks, [doneKey]: !done})}
                      style={{marginTop:3,width:16,height:16,accentColor:roleColor,cursor:'pointer',flexShrink:0}}/>
                    <div style={{flex:1}}>
                      <div style={{fontSize:13,color: done?'#8b9aa7':'#e6edf3',fontWeight:600,textDecoration: done?'line-through':'none'}}>
                        {c.title}
                      </div>
                      <div style={{display:'flex',gap:10,marginTop:4,flexWrap:'wrap'}}>
                        <span style={{fontSize:11,color:'#27c1a3',fontWeight:700}}>{c.hours} CE hours</span>
                        <span style={{fontSize:11,color:'#8b9aa7'}}>Provider: {c.provider}</span>
                        <a href={c.link} target="_blank" rel="noopener noreferrer"
                          style={{fontSize:11,color:'#4da3ff',textDecoration:'none'}}>Visit →</a>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>

            {/* CE hours summary */}
            <div style={{marginTop:16,background:'#0f161d',border:'1px solid #1f2b36',borderRadius:10,padding:'12px 16px'}}>
              <div style={{fontSize:12,fontWeight:700,color:'#e6edf3',marginBottom:6}}>Hours earned this period</div>
              <div style={{fontSize:24,fontWeight:800,color:roleColor}}>
                {CE_SUGGESTIONS[role].reduce((sum,c,i) => checks[`ce_done_${role}_${i}`] ? sum+c.hours : sum, 0)}
                <span style={{fontSize:13,color:'#8b9aa7',fontWeight:400,marginLeft:6}}>/ {CE_SUGGESTIONS[role].reduce((s,c)=>s+c.hours,0)} available CE hours</span>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

window.ComplianceDashboard = ComplianceDashboard;
