/* ============================================================================
 * service-tracker.jsx — 증상별 "트래커 카드" (각 서비스가 추적/관리하는 지표 미니 UI)
 *   window.SvcTrackerCard({ botKey, accent, lang, bot })
 *   kind: bars | ring | line | gauge | checklist  (증상 성격에 맞게)
 * ========================================================================== */

const ST_FONT = '"Pretendard","Inter",system-ui,sans-serif';

// 증상 엠블럼 (추상 아이콘 — 봇과 무관, 독립 사이트 브랜드 마크)
const SVC_G = (c, sw = 2) => ({
  depression: <g stroke={c} strokeWidth={sw} strokeLinecap="round" fill="none"><circle cx="12" cy="12" r="4.2" fill={c} stroke="none" />{[0,45,90,135,180,225,270,315].map((a)=>{const r=a*Math.PI/180;return <line key={a} x1={12+Math.cos(r)*7} y1={12+Math.sin(r)*7} x2={12+Math.cos(r)*9.6} y2={12+Math.sin(r)*9.6} />;})}</g>,
  anxiety: <g stroke={c} strokeWidth={sw} strokeLinecap="round" fill="none"><path d="M3 14 Q7 8 12 14 T21 14" /><path d="M4 18 Q8 13 12 18 T20 18" opacity="0.55" /></g>,
  sleep: <path d="M16.5 13.5 A7 7 0 1 1 10.5 6 A5.5 5.5 0 0 0 16.5 13.5 Z" fill={c} />,
  burnout: <g><path d="M12 19 C5 14 7 6 12 4 C17 6 19 14 12 19 Z" fill={c} /><path d="M12 18 V9" stroke="#0c1020" strokeWidth="1.4" strokeLinecap="round" /></g>,
  ptsd: <path d="M12 3 L19 6 V12 C19 16 16 19 12 21 C8 19 5 16 5 12 V6 Z" fill={c} />,
  ocd: <g stroke={c} strokeWidth={sw} fill="none" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="8.5" /><path d="M8 12 l3 3 5-6" /></g>,
  bipolar: <g><path d="M12 3 a9 9 0 0 0 0 18 a4.5 4.5 0 0 1 0 -9 a4.5 4.5 0 0 0 0 -9 Z" fill={c} /><circle cx="12" cy="7.5" r="1.6" fill="#0c1020" /></g>,
  autism: <g stroke={c} strokeWidth={sw} fill="none"><circle cx="12" cy="12" r="9" /><circle cx="12" cy="12" r="5" /><circle cx="12" cy="12" r="1.6" fill={c} /></g>,
  adhd: <path d="M13 2 L6 13 H11 L10 22 L18 10 H12.5 Z" fill={c} />,
  learning: <g><path d="M8 9 a4 4 0 1 1 8 0 c0 2 -1.5 3 -2 4.5 H10 C9.5 12 8 11 8 9 Z" fill={c} /><path d="M10 18 h4 M10.5 20.5 h3" stroke={c} strokeWidth={sw} strokeLinecap="round" /></g>,
  peak: <g stroke={c} strokeWidth={sw} fill="none"><circle cx="12" cy="12" r="8.5" /><circle cx="12" cy="12" r="4" /><circle cx="12" cy="12" r="1.4" fill={c} stroke="none" /></g>,
});
function SvcGlyph({ k, c, size = 24 }) {
  const G = SVC_G(c);
  return <svg width={size} height={size} viewBox="0 0 24 24" style={{ display: 'block', overflow: 'visible' }}>{G[k] || <circle cx="12" cy="12" r="6" fill={c} />}</svg>;
}

const SVC_TRACK = {
  depression: { kind: 'bars', data: [3, 2, 4, 3, 5, 4, 6],
    label: { en: 'Mood · this week', ko: '기분 · 이번 주' }, metric: { en: '+2 ↑', ko: '+2 ↑' },
    note: { en: 'gently trending up', ko: '조금씩 올라가는 중' } },
  anxiety: { kind: 'ring', value: 72,
    label: { en: 'Calm now', ko: '지금 진정도' }, metric: { en: 'Steady', ko: '안정' },
    note: { en: 'after 3-min breathing', ko: '3분 호흡 후' } },
  sleep: { kind: 'bars', data: [5, 6, 5, 7, 6, 7, 8],
    label: { en: 'Sleep · 7 nights', ko: '수면 · 7일' }, metric: { en: '7h 20m', ko: '7시간 20분' },
    note: { en: 'last night', ko: '어젯밤' } },
  burnout: { kind: 'gauge', value: 46,
    label: { en: 'Energy', ko: '에너지' }, metric: { en: 'Recover today', ko: '오늘은 회복' },
    note: { en: 'below your baseline', ko: '평소보다 낮음' } },
  ptsd: { kind: 'line', data: [2, 3, 3, 4, 5, 5, 6],
    label: { en: 'Calm streak', ko: '안정 연속' }, metric: { en: '6 days', ko: '6일' },
    note: { en: 'steady and safe', ko: '안전하게 꾸준히' } },
  ocd: { kind: 'line', data: [9, 8, 8, 6, 5, 4, 3],
    label: { en: 'Loops · today', ko: '고리 · 오늘' }, metric: { en: '−6', ko: '−6' },
    note: { en: 'easing down', ko: '줄어드는 중' } },
  bipolar: { kind: 'line', data: [4, 6, 5, 3, 4, 6, 5],
    label: { en: 'Mood rhythm', ko: '기분 리듬' }, metric: { en: 'In range', ko: '범위 안' },
    note: { en: 'balanced this week', ko: '이번 주 균형' } },
  autism: { kind: 'checklist',
    items: [{ en: 'Morning plan', ko: '아침 계획', done: true }, { en: 'Sensory break', ko: '감각 휴식', done: true }, { en: 'Wind-down', ko: '마무리 루틴', done: false }],
    label: { en: 'Today routine', ko: '오늘 루틴' }, metric: { en: '2 / 3', ko: '2 / 3' },
    note: { en: 'clear and on track', ko: '또렷하게 진행 중' } },
  adhd: { kind: 'ring', value: 58,
    label: { en: 'Focus today', ko: '오늘 집중' }, metric: { en: '3 sprints', ko: '스프린트 3회' },
    note: { en: 'one more to go', ko: '한 번만 더' } },
  learning: { kind: 'bars', data: [2, 3, 3, 4, 4, 5, 6],
    label: { en: 'Study · this week', ko: '학습 · 이번 주' }, metric: { en: '6-day streak', ko: '6일 연속' },
    note: { en: 'curiosity on a roll', ko: '호기심 순항 중' } },
  peak: { kind: 'gauge', value: 82,
    label: { en: 'Performance', ko: '수행' }, metric: { en: 'Peak zone', ko: '피크 존' },
    note: { en: 'sharp and ready', ko: '예리하게 준비됨' } },
};

function STBars({ data, accent }) {
  const max = Math.max(...data);
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', gap: 6, height: 66 }}>
      {data.map((v, i) => (
        <div key={i} style={{ flex: 1, height: `${Math.max(10, (v / max) * 100)}%`,
          borderRadius: 4, background: i === data.length - 1 ? accent : `${accent}66` }} />
      ))}
    </div>
  );
}
function STRing({ value, accent }) {
  const r = 31, C = 2 * Math.PI * r, off = C * (1 - value / 100);
  return (
    <svg width="86" height="86" viewBox="0 0 86 86">
      <circle cx="43" cy="43" r={r} fill="none" stroke="rgba(0,0,0,0.08)" strokeWidth="7" />
      <circle cx="43" cy="43" r={r} fill="none" stroke={accent} strokeWidth="7" strokeLinecap="round"
        strokeDasharray={C} strokeDashoffset={off} transform="rotate(-90 43 43)" />
      <text x="43" y="49" textAnchor="middle" fill="#2a2018" fontSize="21" fontWeight="800" fontFamily={ST_FONT}>{value}</text>
    </svg>
  );
}
function STLine({ data, accent }) {
  const w = 248, h = 66, max = Math.max(...data), min = Math.min(...data), rng = (max - min) || 1;
  const pts = data.map((v, i) => [i / (data.length - 1) * w, h - ((v - min) / rng) * (h - 14) - 7]);
  const d = pts.map((p, i) => (i ? 'L' : 'M') + p[0].toFixed(1) + ' ' + p[1].toFixed(1)).join(' ');
  const last = pts[pts.length - 1];
  return (
    <svg width={w} height={h} viewBox={`0 0 ${w} ${h}`} style={{ width: '100%' }} preserveAspectRatio="none">
      <path d={d} fill="none" stroke={accent} strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round" />
      <circle cx={last[0]} cy={last[1]} r="4.2" fill={accent} />
    </svg>
  );
}
function STGauge({ value, accent }) {
  const len = Math.PI * 34;
  return (
    <svg width="108" height="64" viewBox="0 0 108 64">
      <path d="M12 50 A34 34 0 0 1 96 50" fill="none" stroke="rgba(0,0,0,0.08)" strokeWidth="8" strokeLinecap="round" />
      <path d="M12 50 A34 34 0 0 1 96 50" fill="none" stroke={accent} strokeWidth="8" strokeLinecap="round"
        strokeDasharray={len} strokeDashoffset={len * (1 - value / 100)} />
      <text x="54" y="46" textAnchor="middle" fill="#2a2018" fontSize="20" fontWeight="800" fontFamily={ST_FONT}>{value}</text>
    </svg>
  );
}
function STChecklist({ items, accent, lang }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
      {items.map((it, i) => (
        <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 9, fontSize: 13, color: '#3a2e26', fontFamily: ST_FONT }}>
          <span style={{ width: 17, height: 17, borderRadius: 5, flexShrink: 0,
            border: `1.5px solid ${it.done ? accent : 'rgba(255,255,255,0.3)'}`,
            background: it.done ? accent : 'transparent',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
            {it.done && <svg width="9" height="9" viewBox="0 0 10 10"><path d="M1 5 L4 8 L9 2" fill="none" stroke="#0c1020" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /></svg>}
          </span>
          <span style={{ opacity: it.done ? 1 : 0.62 }}>{lang === 'en' ? it.en : it.ko}</span>
        </div>
      ))}
    </div>
  );
}

function SvcTrackerCard({ botKey, accent, lang, bot }) {
  const t = SVC_TRACK[botKey] || SVC_TRACK.depression;
  const L = (o) => (lang === 'en' ? o.en : o.ko);
  let viz = null;
  if (t.kind === 'bars') viz = <STBars data={t.data} accent={accent} />;
  else if (t.kind === 'ring') viz = <div style={{ display: 'flex', justifyContent: 'center' }}><STRing value={t.value} accent={accent} /></div>;
  else if (t.kind === 'line') viz = <STLine data={t.data} accent={accent} />;
  else if (t.kind === 'gauge') viz = <div style={{ display: 'flex', justifyContent: 'center' }}><STGauge value={t.value} accent={accent} /></div>;
  else if (t.kind === 'checklist') viz = <STChecklist items={t.items} accent={accent} lang={lang} />;

  return (
    <div style={{ width: 300, borderRadius: 18, padding: '16px 18px',
      background: 'rgba(255,255,255,0.95)', backdropFilter: 'blur(10px)',
      border: `1px solid ${accent}55`, boxShadow: '0 18px 44px rgba(80,60,40,0.18)', fontFamily: ST_FONT }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14 }}>
        <span style={{ width: 24, height: 24, borderRadius: 7, background: `${accent}22`,
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
          <SvcGlyph k={botKey} c={accent} size={15} />
        </span>
        <span style={{ fontSize: 12.5, fontWeight: 700, color: '#5a4a3a', letterSpacing: '0.01em' }}>{L(t.label)}</span>
        <span style={{ marginLeft: 'auto', width: 6, height: 6, borderRadius: '50%', background: accent, boxShadow: `0 0 8px ${accent}` }} />
      </div>
      <div style={{ minHeight: 66, display: 'flex', alignItems: 'center' }}>{viz}</div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 14,
        borderTop: '1px solid rgba(0,0,0,0.08)', paddingTop: 12 }}>
        <span style={{ fontSize: 17, fontWeight: 800, color: '#2a2018' }}>{L(t.metric)}</span>
        <span style={{ fontSize: 12, color: '#9a8a78' }}>{L(t.note)}</span>
      </div>
    </div>
  );
}

Object.assign(window, { SvcTrackerCard, SvcGlyph });
