// Health Dashboard — Bengkel Mitra Sejahtera
// Signature page: vehicle anatomy SVG dengan komponen clickable

function HealthPage({ role }) {
  const [selectedVh, setSelectedVh] = useState(KENDARAAN[0]);
  const [selectedComp, setSelectedComp] = useState(null);
  const [search, setSearch] = useState('');

  // sort: paling perlu perhatian dulu
  const sortedVeh = useMemo(() => [...KENDARAAN].sort((a,b) => (healthScore(a) || 0) - (healthScore(b) || 0)), []);
  const filtered = sortedVeh.filter(v => {
    if (!search) return true;
    const owner = OWNER_BY_ID[v.ownerId]?.name || '';
    return (`${v.plat} ${v.merk} ${v.model} ${owner}`).toLowerCase().includes(search.toLowerCase());
  });

  const score = healthScore(selectedVh);
  const tone = scoreTone(score);
  const nextSvc = vehicleNextService(selectedVh);

  return (
    <div>
      <PageHeader
        eyebrow="Visualisasi Real-time"
        title="Vehicle Health Dashboard"
        subtitle="Anatomi kendaraan interaktif — klik komponen untuk detail. Customer juga melihat tampilan ini di app mereka."
        actions={<Btn icon="download" tone="outline">Export Report</Btn>}
      />

      <div className="health-shell">
        {/* LEFT: vehicle list */}
        <div className="health-list">
          <div className="health-list-head">
            <span style={{fontSize:13, fontWeight:600}}>Kendaraan ({filtered.length})</span>
            <span style={{fontSize:11, color:'hsl(var(--muted-foreground))'}}>Diurutkan paling kritis</span>
          </div>
          <div style={{padding:'8px 12px', borderBottom:'1px solid hsl(var(--border))'}}>
            <div style={{position:'relative'}}>
              <Icon name="search" size={13} style={{position:'absolute', left:8, top:'50%', transform:'translateY(-50%)', color:'hsl(var(--muted-foreground))'}} />
              <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Cari kendaraan..."
                style={{width:'100%', padding:'6px 8px 6px 28px', border:'1px solid hsl(var(--border))', borderRadius:6, fontSize:12.5, background:'hsl(var(--background))'}} />
            </div>
          </div>
          <div className="health-list-scroll">
            {filtered.map(v => {
              const s = healthScore(v);
              const t = scoreTone(s);
              const ownr = OWNER_BY_ID[v.ownerId];
              return (
                <div key={v.id}
                  className={'health-list-item' + (selectedVh.id === v.id ? ' active' : '')}
                  onClick={() => { setSelectedVh(v); setSelectedComp(null); }}>
                  <Icon name={v.tipe === 'motor' ? 'motorbike' : v.tipe === 'komersial' ? 'truck' : 'car'} size={20} />
                  <div style={{minWidth:0}}>
                    <div className="row gap-1" style={{alignItems:'center'}}>
                      <span className="plate">{v.plat}</span>
                    </div>
                    <div className="label" style={{marginTop:3}}>{v.merk} {v.model}</div>
                    <div className="meta">{ownr?.name?.split(' ').slice(0,2).join(' ') || '—'} · {v.km.toLocaleString('id-ID')} km</div>
                  </div>
                  <HealthBadge tone={t}>{s ?? '—'}</HealthBadge>
                </div>
              );
            })}
          </div>
        </div>

        {/* CENTER: anatomy stage */}
        <div className="health-stage">
          <div className="health-stage-info">
            <div style={{fontWeight:650}}>{selectedVh.merk} {selectedVh.model}</div>
            <div style={{fontSize:11.5, color:'hsl(var(--muted-foreground))', marginTop:2}}>
              <span className="mono">{selectedVh.plat}</span> · {selectedVh.tahun} · {selectedVh.km.toLocaleString('id-ID')} km
            </div>
          </div>
          <div className="health-stage-score">
            <div>
              <div style={{fontSize:10, textTransform:'uppercase', letterSpacing:'.05em', color:'hsl(var(--muted-foreground))', fontWeight:600}}>Health Score</div>
              <div className={'health-score-num ' + tone}>{score ?? '—'}</div>
            </div>
            <div style={{borderLeft:'1px solid hsl(var(--border))', paddingLeft:10}}>
              <HealthBadge tone={tone}>{scoreLabel(score)}</HealthBadge>
              {nextSvc && <div style={{fontSize:11, color:'hsl(var(--muted-foreground))', marginTop:4}}>Prioritas: {nextSvc.label}</div>}
            </div>
          </div>

          <VehicleAnatomy vehicle={selectedVh} selectedComp={selectedComp} onSelect={setSelectedComp} />
        </div>

        {/* RIGHT: component detail */}
        <div className="health-detail">
          <div className="health-detail-head">
            <span style={{fontSize:13, fontWeight:600}}>{selectedComp ? HEALTH_COMP_BY_ID[selectedComp]?.label : 'Semua komponen'}</span>
            {selectedComp && <Btn size="sm" tone="ghost" icon="x" onClick={() => setSelectedComp(null)} />}
          </div>

          {selectedComp ? (
            <ComponentDetail vehicle={selectedVh} compId={selectedComp} />
          ) : (
            <div style={{padding:14, overflowY:'auto', flex:1}}>
              <div className="gauge-cluster" style={{padding:0, marginBottom:14}}>
                {HEALTH_COMPONENTS.map(c => {
                  const r = componentRatio(selectedVh, c.id);
                  if (r == null) return null;
                  return (
                    <div key={c.id} className="mini-gauge" onClick={() => setSelectedComp(c.id)} style={{cursor:'pointer'}}>
                      <div className="mini-gauge-label"><Icon name={c.icon} size={12} /> {c.label}</div>
                      <div className="mini-gauge-val">{Math.round(r * 100)}%</div>
                      <div className="mini-gauge-bar"><div className={'fill ' + componentTone(r)} style={{width: Math.min(100, r*100) + '%'}} /></div>
                    </div>
                  );
                })}
              </div>

              <SectionHead title="Dokumen kendaraan" />
              <div className="doc-strip" style={{marginBottom:14}}>
                {[
                  { kind:'STNK',     iso: selectedVh.stnkExp },
                  { kind:'Pajak',    iso: selectedVh.pajakExp },
                  { kind:'Asuransi', iso: selectedVh.asuransiExp },
                  selectedVh.kirExp ? { kind:'KIR', iso: selectedVh.kirExp } : null,
                ].filter(Boolean).map(d => {
                  const days = daysToExpiry(d.iso);
                  const lvl = dueLevel(days);
                  return (
                    <div key={d.kind} className={'doc-chip' + (lvl === 'danger' || lvl === 'overdue' ? ' urgent' : lvl === 'warn' ? ' warn' : '')}>
                      <div className="doc-chip-head">{d.kind}</div>
                      <div className="doc-chip-val">{formatDateID(d.iso)}</div>
                      <div className="doc-chip-sub">{dueLabel(days)}</div>
                    </div>
                  );
                })}
              </div>

              <div className="row gap-2" style={{marginTop:'auto'}}>
                <Btn icon="calendar" size="sm">Booking</Btn>
                <Btn tone="outline" size="sm" icon="whatsapp">Kirim WA</Btn>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ── Anatomy SVG ───────────────────────────────────────────────────────────

function VehicleAnatomy({ vehicle, selectedComp, onSelect }) {
  const isMotor = vehicle.tipe === 'motor';
  const isKomersial = vehicle.tipe === 'komersial';

  const compClass = (compId) => {
    const r = componentRatio(vehicle, compId);
    const tone = componentTone(r);
    return 'comp-' + (tone === 'good' ? 'good' : tone === 'warn' ? 'warn' : 'danger') +
           (selectedComp === compId ? ' selected' : '');
  };

  if (isMotor) {
    return (
      <svg className="health-anatomy" viewBox="0 0 520 280" xmlns="http://www.w3.org/2000/svg">
        {/* shadow */}
        <ellipse cx="260" cy="245" rx="200" ry="10" fill="#000" opacity="0.06" />
        {/* body sport bike side */}
        <path d="M 110 200 L 130 160 L 200 140 L 270 130 L 320 120 L 380 130 L 410 160 L 410 200 Z"
          fill="#cbd5e1" stroke="#475569" strokeWidth="1.2" opacity="0.5" />
        {/* seat */}
        <path d="M 260 130 L 370 125 L 380 145 L 280 150 Z" fill="#1f2937" />
        {/* handlebar */}
        <path d="M 380 130 L 410 95 L 440 95" stroke="#475569" strokeWidth="3" fill="none" strokeLinecap="round" />
        {/* fork */}
        <line x1="395" y1="155" x2="420" y2="210" stroke="#475569" strokeWidth="2.5" />
        <line x1="135" y1="160" x2="115" y2="210" stroke="#475569" strokeWidth="2.5" />

        {/* wheels (ban) */}
        <g data-component="ban" onClick={() => onSelect('ban')}>
          <circle cx="115" cy="220" r="38" className={compClass('ban')} strokeWidth="3" />
          <circle cx="115" cy="220" r="14" fill="#94a3b8" />
          <circle cx="420" cy="220" r="38" className={compClass('ban')} strokeWidth="3" />
          <circle cx="420" cy="220" r="14" fill="#94a3b8" />
        </g>

        {/* brake disc (rem) */}
        <g data-component="rem_dpn" onClick={() => onSelect('rem_dpn')}>
          <circle cx="420" cy="220" r="22" className={compClass('rem_dpn')} strokeWidth="2" opacity="0.85" />
        </g>
        <g data-component="rem_blk" onClick={() => onSelect('rem_blk')}>
          <circle cx="115" cy="220" r="22" className={compClass('rem_blk')} strokeWidth="2" opacity="0.85" />
        </g>

        {/* engine */}
        <g data-component="oli_mesin" onClick={() => onSelect('oli_mesin')}>
          <rect x="220" y="165" width="80" height="55" rx="6" className={compClass('oli_mesin')} strokeWidth="2" />
          <text x="260" y="195" textAnchor="middle" fontSize="10" fontWeight="700" fill="#1e293b">ENGINE</text>
        </g>

        {/* aki under seat */}
        <g data-component="aki" onClick={() => onSelect('aki')}>
          <rect x="305" y="155" width="40" height="28" rx="3" className={compClass('aki')} strokeWidth="1.5" />
        </g>

        {/* busi (small) */}
        <g data-component="busi" onClick={() => onSelect('busi')}>
          <circle cx="240" cy="158" r="8" className={compClass('busi')} strokeWidth="1.5" />
        </g>

        {/* air filter (filter_udr) */}
        <g data-component="filter_udr" onClick={() => onSelect('filter_udr')}>
          <rect x="195" y="170" width="22" height="22" rx="2" className={compClass('filter_udr')} strokeWidth="1.5" />
        </g>

        {/* radiator (only for motor besar — show small) */}
        <g data-component="radiator" onClick={() => onSelect('radiator')}>
          <rect x="305" y="190" width="30" height="22" rx="2" className={compClass('radiator')} strokeWidth="1.5" />
        </g>

        {/* labels */}
        <text x="115" y="270" textAnchor="middle" fontSize="9" fill="#64748b" fontWeight="600">Ban / Rem Blkg</text>
        <text x="420" y="270" textAnchor="middle" fontSize="9" fill="#64748b" fontWeight="600">Ban / Rem Dpn</text>
        <text x="260" y="100" textAnchor="middle" fontSize="9" fill="#64748b" fontWeight="600">Klik komponen untuk detail</text>
      </svg>
    );
  }

  // Mobil/komersial — 3/4 isometric-ish
  return (
    <svg className="health-anatomy" viewBox="0 0 520 320" xmlns="http://www.w3.org/2000/svg">
      <ellipse cx="260" cy="285" rx="220" ry="12" fill="#000" opacity="0.06" />

      {/* Body — perspective shape */}
      <path d="M 90 235 L 100 175 Q 110 145 145 138 L 175 95 Q 195 80 240 80 L 360 80 Q 405 80 425 100 L 450 145 Q 480 152 488 180 L 495 235 L 470 245 L 450 245 L 440 235 L 380 235 L 365 245 L 155 245 L 140 235 L 80 235 Z"
        fill={isKomersial ? '#fde68a' : '#bae6fd'} stroke="#475569" strokeWidth="1.5" opacity="0.5" />

      {/* Cargo for komersial */}
      {isKomersial && (
        <rect x="280" y="105" width="170" height="130" rx="4" fill="#fcd34d" stroke="#475569" strokeWidth="1.5" opacity="0.6" />
      )}

      {/* Windows */}
      {!isKomersial && <path d="M 195 95 L 215 145 L 405 145 L 385 95 Z" fill="#cbd5e1" stroke="#475569" strokeWidth="1" opacity="0.6" />}

      {/* Wheels — 4 */}
      <g data-component="ban" onClick={() => onSelect('ban')}>
        <circle cx="155" cy="245" r="32" className={compClass('ban')} strokeWidth="3" />
        <circle cx="155" cy="245" r="12" fill="#94a3b8" />
        <circle cx="395" cy="245" r="32" className={compClass('ban')} strokeWidth="3" />
        <circle cx="395" cy="245" r="12" fill="#94a3b8" />
      </g>

      {/* Brake discs */}
      <g data-component="rem_dpn" onClick={() => onSelect('rem_dpn')}>
        <circle cx="395" cy="245" r="18" className={compClass('rem_dpn')} strokeWidth="2" opacity="0.8" />
      </g>
      <g data-component="rem_blk" onClick={() => onSelect('rem_blk')}>
        <circle cx="155" cy="245" r="18" className={compClass('rem_blk')} strokeWidth="2" opacity="0.8" />
      </g>

      {/* Engine bay (front) */}
      <g data-component="oli_mesin" onClick={() => onSelect('oli_mesin')}>
        <rect x="380" y="155" width="80" height="60" rx="6" className={compClass('oli_mesin')} strokeWidth="2" />
        <text x="420" y="190" textAnchor="middle" fontSize="11" fontWeight="700" fill="#1e293b">ENGINE</text>
      </g>

      {/* Filter oli + udara — small boxes inside engine bay */}
      <g data-component="filter_oli" onClick={() => onSelect('filter_oli')}>
        <circle cx="395" cy="170" r="8" className={compClass('filter_oli')} strokeWidth="1.5" />
      </g>
      <g data-component="filter_udr" onClick={() => onSelect('filter_udr')}>
        <rect x="408" y="200" width="20" height="10" rx="2" className={compClass('filter_udr')} strokeWidth="1.5" />
      </g>

      {/* Aki — front corner */}
      <g data-component="aki" onClick={() => onSelect('aki')}>
        <rect x="438" y="160" width="22" height="20" rx="2" className={compClass('aki')} strokeWidth="1.5" />
        <line x1="442" y1="160" x2="442" y2="156" stroke="#475569" strokeWidth="2" />
        <line x1="456" y1="160" x2="456" y2="156" stroke="#475569" strokeWidth="2" />
      </g>

      {/* Busi (4 dots inside engine) */}
      <g data-component="busi" onClick={() => onSelect('busi')}>
        <circle cx="398" cy="185" r="3" className={compClass('busi')} strokeWidth="1" />
        <circle cx="410" cy="185" r="3" className={compClass('busi')} strokeWidth="1" />
        <circle cx="422" cy="185" r="3" className={compClass('busi')} strokeWidth="1" />
        <circle cx="434" cy="185" r="3" className={compClass('busi')} strokeWidth="1" />
      </g>

      {/* Transmisi (middle floor) */}
      <g data-component="oli_trans" onClick={() => onSelect('oli_trans')}>
        <rect x="270" y="195" width="70" height="30" rx="4" className={compClass('oli_trans')} strokeWidth="1.5" />
        <text x="305" y="215" textAnchor="middle" fontSize="9" fontWeight="600" fill="#1e293b">TRANS</text>
      </g>

      {/* Kopling (next to trans) */}
      <g data-component="kopling" onClick={() => onSelect('kopling')}>
        <circle cx="350" cy="210" r="13" className={compClass('kopling')} strokeWidth="1.5" />
      </g>

      {/* AC — front of cabin */}
      <g data-component="ac" onClick={() => onSelect('ac')}>
        <rect x="330" y="155" width="42" height="22" rx="3" className={compClass('ac')} strokeWidth="1.5" />
        <text x="351" y="170" textAnchor="middle" fontSize="9" fontWeight="600" fill="#1e293b">A/C</text>
      </g>

      {/* Radiator — very front */}
      <g data-component="radiator" onClick={() => onSelect('radiator')}>
        <rect x="465" y="190" width="14" height="40" rx="2" className={compClass('radiator')} strokeWidth="1.5" />
      </g>

      <text x="260" y="65" textAnchor="middle" fontSize="10" fill="#64748b" fontWeight="600">Klik komponen untuk detail · hover untuk highlight</text>
    </svg>
  );
}

// ── Component detail panel ───────────────────────────────────────────────

function ComponentDetail({ vehicle, compId }) {
  const def = HEALTH_COMP_BY_ID[compId];
  const cur = vehicle.components[compId];
  if (!def || !cur) return <div style={{padding:14, color:'hsl(var(--muted-foreground))', fontSize:13}}>Komponen tidak tersedia untuk kendaraan ini.</div>;

  const r = componentRatio(vehicle, compId);
  const tone = componentTone(r);
  const pct = Math.min(100, Math.round(r * 100));
  const sisaKm = Math.max(0, def.intervalKm - cur.km);
  const sisaMo = Math.max(0, def.intervalMo - cur.mo);
  const rekomMerk = {
    oli_mesin:  ['Shell Helix HX7 10W-40', 'Castrol Magnatec 10W-40', 'Pertamina Fastron'],
    filter_oli: ['Aspira Premium', 'Sakura Original', 'Denso'],
    filter_udr: ['Aspira HEPA', 'Sakura', 'K&N (sport)'],
    aki:        ['GS Hybrid NS40Z', 'Incoe N50', 'Yuasa Premium'],
    rem_dpn:    ['Bendix MKC', 'Brembo', 'Akebono Asbestos-Free'],
    rem_blk:    ['Bendix MKC', 'Brembo', 'Akebono'],
    ban:        ['Bridgestone Turanza', 'Dunlop SP Sport', 'Michelin Energy'],
    busi:       ['NGK Iridium IX', 'Denso Iridium TT', 'Champion'],
    ac:         ['Klea R134a + Cuci evap', 'Honeywell freon original'],
    kopling:    ['Aisin OEM set', 'Daikin original', 'Exedy sport'],
    radiator:   ['Prestone Coolant', 'Toyota Genuine', 'Pertamina Cooler'],
    oli_trans:  ['Shell Spirax ATF', 'Castrol Transmax', 'Pertamina ATF'],
  }[compId] || ['—'];

  return (
    <div style={{padding:14, overflowY:'auto', flex:1, display:'flex', flexDirection:'column', gap:14}}>
      <div>
        <div className="row gap-2" style={{alignItems:'center', marginBottom:8}}>
          <Icon name={def.icon} size={18} />
          <span style={{fontSize:16, fontWeight:650}}>{def.label}</span>
          <span style={{flex:1}} />
          <HealthBadge tone={tone}>{pct}%</HealthBadge>
        </div>
        <div className="reminder-progress" style={{height:8, marginBottom:6}}>
          <div className={'bar ' + tone} style={{width: pct + '%'}} />
        </div>
        <div style={{fontSize:11.5, color:'hsl(var(--muted-foreground))'}}>
          Pemakaian sejak servis terakhir
        </div>
      </div>

      <div className="grid" style={{gridTemplateColumns:'1fr 1fr', gap:10}}>
        <div style={{padding:'10px 12px', background:'hsl(var(--muted) / 0.5)', borderRadius:8}}>
          <div style={{fontSize:11, color:'hsl(var(--muted-foreground))', fontWeight:600, textTransform:'uppercase', letterSpacing:'.04em'}}>Interval Standar</div>
          <div style={{fontSize:18, fontWeight:650, marginTop:4}}>{def.intervalKm.toLocaleString('id-ID')} km</div>
          <div style={{fontSize:12, color:'hsl(var(--muted-foreground))'}}>atau {def.intervalMo} bulan</div>
        </div>
        <div style={{padding:'10px 12px', background:'hsl(var(--muted) / 0.5)', borderRadius:8}}>
          <div style={{fontSize:11, color:'hsl(var(--muted-foreground))', fontWeight:600, textTransform:'uppercase', letterSpacing:'.04em'}}>Pemakaian Saat Ini</div>
          <div style={{fontSize:18, fontWeight:650, marginTop:4}}>{cur.km.toLocaleString('id-ID')} km</div>
          <div style={{fontSize:12, color:'hsl(var(--muted-foreground))'}}>+ {cur.mo} bulan</div>
        </div>
        <div style={{padding:'10px 12px', background:'hsl(var(--muted) / 0.5)', borderRadius:8}}>
          <div style={{fontSize:11, color:'hsl(var(--muted-foreground))', fontWeight:600, textTransform:'uppercase', letterSpacing:'.04em'}}>Sisa</div>
          <div style={{fontSize:18, fontWeight:650, marginTop:4, color: tone === 'danger' ? 'hsl(0 72% 42%)' : tone === 'warn' ? 'hsl(28 80% 40%)' : 'hsl(158 60% 32%)'}}>{sisaKm.toLocaleString('id-ID')} km</div>
          <div style={{fontSize:12, color:'hsl(var(--muted-foreground))'}}>atau {sisaMo} bulan</div>
        </div>
        <div style={{padding:'10px 12px', background:'hsl(var(--muted) / 0.5)', borderRadius:8}}>
          <div style={{fontSize:11, color:'hsl(var(--muted-foreground))', fontWeight:600, textTransform:'uppercase', letterSpacing:'.04em'}}>Status</div>
          <div style={{fontSize:14, fontWeight:650, marginTop:6}}>
            {tone === 'good' ? 'Sehat ✓' : tone === 'warn' ? 'Mendekati Servis' : 'Servis Segera'}
          </div>
        </div>
      </div>

      <div>
        <SectionHead title="Rekomendasi merk sparepart" hint="Berdasarkan riwayat servis & rekomendasi pabrikan" />
        <div className="flex-col gap-1">
          {rekomMerk.map((m, i) => (
            <div key={m} className="row gap-2" style={{padding:'8px 10px', background:'hsl(var(--card))', border:'1px solid hsl(var(--border))', borderRadius:6, alignItems:'center'}}>
              <span style={{fontSize:11, fontWeight:700, color:'hsl(var(--accent-h) var(--accent-s) 38%)', minWidth:18}}>#{i+1}</span>
              <span style={{fontSize:13, flex:1}}>{m}</span>
              {i === 0 && <Pill tone="accent">Recommended</Pill>}
            </div>
          ))}
        </div>
      </div>

      <div className="row gap-2" style={{marginTop:'auto'}}>
        <Btn icon="calendar">Booking Servis</Btn>
        <Btn tone="outline" icon="package">Cek Sparepart</Btn>
      </div>
    </div>
  );
}

window.HealthPage = HealthPage;
