// ABO Tracking — active downlines & members studying in the Emphasis system.

function AboView() {
  const [tab, setTab] = useState('list');
  const [selectedId, setSelectedId] = useState(window.ABO_LIST[0].id);
  const [query, setQuery] = useState('');
  const [roleFilter, setRoleFilter] = useState('all');

  const list = useMemo(() => window.ABO_LIST.filter(a =>
    (roleFilter === 'all' || a.role === roleFilter) &&
    (!query.trim() || a.name.includes(query) || a.abo.includes(query))
  ), [query, roleFilter]);

  const active = window.ABO_LIST.filter(a => a.active).length;
  const newThisMonth = window.ABO_LIST.filter(a => new Date(a.joinDate) > new Date('2025-10-01')).length;
  const focused = window.ABO_LIST.filter(a => a.focus).length;
  const avgBT = (window.ABO_LIST.reduce((s, a) => s + a.btScore, 0) / window.ABO_LIST.length * 100).toFixed(0);

  const selected = window.ABO_LIST.find(a => a.id === selectedId);

  return (
    <div className="space-y-5">
      <SectionHead
        eyebrow="Module · ABO Tracking"
        title="คนที่กำลังศึกษาในระบบ Emphasis"
        sub="รายชื่อ DL ที่ Active, รายละเอียดการเรียนรู้, ความคืบหน้า BT Qualification, และสถิติการลงมือทำ"
        right={
          <div className="flex items-center gap-2">
            <Btn variant="ghost" size="sm" icon={<Icon name="filter" />}>Export</Btn>
            <Btn variant="brand" size="sm" icon={<Icon name="plus" />}>เพิ่ม DL</Btn>
          </div>
        }
      />

      {/* Vital signs row (moved here from old Leader Dashboard) */}
      <div className="grid grid-cols-12 gap-4">
        <Card className="col-span-12 lg:col-span-5 bg-gradient-to-br from-ink-900 to-brand-700 text-white border-ink-700" pad={false}>
          <div className="p-5 flex items-center gap-5">
            <Ring value={0.55} max={1} size={108} stroke={10} color="#FFB400" track="rgba(255,255,255,0.15)">
              <div className="text-center">
                <div className="text-xl font-semibold num">55%</div>
                <div className="text-[9px] uppercase tracking-wider opacity-60">org goal</div>
              </div>
            </Ring>
            <div className="flex-1">
              <div className="text-[11px] uppercase tracking-[0.14em] font-semibold text-gold-300">Org PPV เดือนนี้</div>
              <div className="flex items-baseline gap-2 mt-1">
                <span className="text-3xl font-semibold num">16,500</span>
                <span className="text-sm text-white/60 num">/ 30,000</span>
              </div>
              <div className="text-xs text-white/60 mt-1">ขาด 13,500 PV · 17 วันที่เหลือ</div>
            </div>
          </div>
        </Card>

        <div className="col-span-12 lg:col-span-7">
          <Card pad={false}>
            <div className="grid grid-cols-2 md:grid-cols-4 divide-x divide-ink-100">
              <div className="p-4">
                <Stat label="Active DL" value={active} sub={`/ ${window.ABO_LIST.length} total`} accent="#10B981" trend={8} />
              </div>
              <div className="p-4">
                <Stat label="ใหม่เดือนนี้" value={newThisMonth} sub="คน" accent="#2F5DE5" trend={20} />
              </div>
              <div className="p-4">
                <Stat label="Focus 5" value={focused} sub="คน" accent="#7C3AED" />
              </div>
              <div className="p-4">
                <Stat label="BT Score เฉลี่ย" value={`${avgBT}%`} sub="across team" accent="#F59E0B" />
              </div>
            </div>
          </Card>
        </div>
      </div>

      {/* Tabs */}
      <Tabs
        variant="underline"
        active={tab}
        onChange={setTab}
        tabs={[
          { id: 'list',  label: 'รายชื่อ DL', icon: <Icon name="users" className="w-3.5 h-3.5" /> },
          { id: 'tree',  label: 'โครงสร้างองค์กร', icon: <Icon name="users" className="w-3.5 h-3.5" /> },
          { id: 'study', label: 'ความคืบหน้าการเรียน', icon: <Icon name="book" className="w-3.5 h-3.5" /> },
        ]}
      />

      {tab === 'list' && (
        <div className="grid grid-cols-12 gap-4">
          {/* Table */}
          <Card className="col-span-12 lg:col-span-7" pad={false}>
            <div className="px-5 pt-4 pb-3 border-b border-ink-100 flex items-center gap-3">
              <div className="relative flex-1">
                <Icon name="search" className="absolute left-3 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-ink-400" />
                <input value={query} onChange={e => setQuery(e.target.value)}
                       placeholder="ค้นหาชื่อ หรือ ABO code..."
                       className="w-full h-9 pl-9 pr-3 text-xs border border-ink-200 rounded-lg outline-none focus:border-brand-500" />
              </div>
              <div className="flex gap-1">
                {['all', 'BT', 'ABO', 'Member'].map(r => (
                  <button key={r} onClick={() => setRoleFilter(r)}
                    className={`text-[11px] font-medium px-2 py-1.5 rounded-md transition-all ${roleFilter === r ? 'bg-ink-900 text-white' : 'text-ink-500 hover:bg-ink-50'}`}>
                    {r === 'all' ? 'ทั้งหมด' : r}
                  </button>
                ))}
              </div>
            </div>

            <div className="max-h-[640px] overflow-y-auto scroll-thin">
              <table className="w-full text-xs">
                <thead className="sticky top-0 bg-white border-b border-ink-100">
                  <tr className="text-ink-400 text-[10px] uppercase tracking-wider">
                    <th className="text-left font-medium px-5 py-2">ABO / Member</th>
                    <th className="text-left font-medium pr-3 py-2">Pin</th>
                    <th className="text-right font-medium pr-3 py-2">PPV</th>
                    <th className="text-center font-medium pr-3 py-2">DL</th>
                    <th className="text-left font-medium pr-5 py-2">BT Score</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-ink-100">
                  {list.map(a => {
                    const isSel = a.id === selectedId;
                    const country = window.COUNTRIES.find(c => c.id === a.country);
                    return (
                      <tr key={a.id} onClick={() => setSelectedId(a.id)}
                          className={`cursor-pointer transition-colors ${isSel ? 'bg-brand-50/50' : 'hover:bg-ink-50/50'}`}>
                        <td className="px-5 py-3">
                          <div className="flex items-center gap-2.5">
                            <div className="relative">
                              <Avatar user={{ avatar: a.name.charAt(0), color: a.active ? '#2F5DE5' : '#94A3B8' }} size={28} />
                              <span className={`absolute -bottom-0.5 -right-0.5 w-2.5 h-2.5 rounded-full border-2 border-white ${a.active ? 'bg-emerald-500' : 'bg-ink-300'}`} />
                            </div>
                            <div className="min-w-0">
                              <div className="flex items-center gap-1.5">
                                <span className="font-semibold text-ink-900 truncate">{a.name}</span>
                                {country && a.country !== 'th' && <span className="text-xs leading-none">{country.flag}</span>}
                                {a.focus && <Pill color="#7C3AED" tint="#F3EFFE" size="xs">⭐ Focus</Pill>}
                              </div>
                              <div className="text-[10px] num text-ink-400">{a.abo} · {a.lastLogin} ago</div>
                            </div>
                          </div>
                        </td>
                        <td className="pr-3 py-3">
                          <Pill color={pinColor(a.pin).c} tint={pinColor(a.pin).t} size="xs">{a.pin}</Pill>
                        </td>
                        <td className="pr-3 py-3 text-right font-semibold num text-ink-800">{a.ppv.toLocaleString()}</td>
                        <td className="pr-3 py-3 text-center">
                          <span className={`inline-flex w-6 h-6 rounded-md items-center justify-center font-semibold ${a.downlines > 0 ? 'bg-emerald-50 text-emerald-600' : 'bg-ink-50 text-ink-300'}`}>{a.downlines}</span>
                        </td>
                        <td className="pr-5 py-3 w-[140px]">
                          <div className="flex items-center gap-2">
                            <Bar value={a.btScore} color={a.btScore >= 0.7 ? '#10B981' : a.btScore >= 0.4 ? '#2F5DE5' : '#F59E0B'} height={4} />
                            <span className="text-[10px] num text-ink-500 w-8 text-right">{Math.round(a.btScore*100)}%</span>
                          </div>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </Card>

          {/* Detail */}
          {selected && (
            <Card className="col-span-12 lg:col-span-5" pad={false}>
              <AboDetail abo={selected} />
            </Card>
          )}
        </div>
      )}

      {tab === 'tree' && <OrgTree />}

      {tab === 'study' && <StudyProgress />}
    </div>
  );
}

function pinColor(pin) {
  const map = {
    'Diamond':   { c: '#1B379F', t: '#EEF4FF' },
    'Emerald':   { c: '#10B981', t: '#E7F8F1' },
    'Platinum':  { c: '#7C3AED', t: '#F3EFFE' },
    '21%':       { c: '#1B379F', t: '#EEF4FF' },
    '18%':       { c: '#2F5DE5', t: '#EEF4FF' },
    '15%':       { c: '#2F5DE5', t: '#EEF4FF' },
    '12%':       { c: '#8B5CF6', t: '#F3EFFE' },
    '9%':        { c: '#10B981', t: '#E7F8F1' },
    'New':       { c: '#94A3B8', t: '#F1F5F9' },
  };
  return map[pin] || map['9%'];
}

function AboDetail({ abo }) {
  const country = window.COUNTRIES.find(c => c.id === abo.country);
  const upline = window.UPLINES.find(u => u.id === abo.upline) || window.ABO_LIST.find(u => u.id === abo.upline);
  return (
    <div>
      {/* Header */}
      <div className="p-5 bg-gradient-to-br from-brand-50 to-white border-b border-ink-100">
        <div className="flex items-start gap-3">
          <Avatar user={{ avatar: abo.name.charAt(0), color: '#2F5DE5' }} size={56} />
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2">
              <h2 className="text-base font-semibold text-ink-900">{abo.name}</h2>
              {country && <span className="text-base leading-none">{country.flag}</span>}
              {abo.focus && <Pill color="#7C3AED" tint="#F3EFFE" size="xs">⭐ Focus</Pill>}
            </div>
            <div className="text-[11px] text-ink-500 num mt-0.5">{abo.abo} · เข้าระบบ {abo.joinDate}</div>
            <div className="flex items-center gap-2 mt-2">
              <Pill color={pinColor(abo.pin).c} tint={pinColor(abo.pin).t} size="xs">{abo.pin}</Pill>
              <Pill color={abo.role === 'BT' ? '#2F5DE5' : abo.role === 'ABO' ? '#10B981' : '#94A3B8'} tint={abo.role === 'BT' ? '#EEF4FF' : abo.role === 'ABO' ? '#E7F8F1' : '#F1F5F9'} size="xs">{abo.role}</Pill>
              {abo.badge && <Pill color="#B87C00" tint="#FFECB8" size="xs">🏆 {abo.badge}</Pill>}
            </div>
          </div>
        </div>
      </div>

      {/* Metrics grid */}
      <div className="p-5 space-y-4">
        <div className="grid grid-cols-3 gap-2">
          {[
            { label: 'PPV',         value: abo.ppv.toLocaleString(),       color: '#10B981' },
            { label: 'Downlines',   value: abo.downlines,                  color: '#2F5DE5' },
            { label: 'Prospects',   value: abo.prospects,                  color: '#8B5CF6' },
            { label: 'EM Packs',    value: `${abo.emPack}/15`,             color: '#F59E0B' },
            { label: 'MFinity',     value: abo.mfin,                       color: '#EC4899' },
            { label: 'House Mtg',   value: abo.hm,                         color: '#06B6D4' },
          ].map(m => (
            <div key={m.label} className="rounded-lg border border-ink-100 p-2.5 bg-white">
              <div className="text-[10px] uppercase tracking-wider text-ink-400">{m.label}</div>
              <div className="text-base font-semibold num" style={{ color: m.color }}>{m.value}</div>
            </div>
          ))}
        </div>

        {/* Progress bars */}
        <div className="space-y-3">
          <div>
            <div className="flex items-center justify-between mb-1">
              <span className="text-[11px] font-medium text-ink-700">BT Qualification</span>
              <span className="text-[11px] num text-ink-500">{Math.round(abo.btScore * 100)}%</span>
            </div>
            <Bar value={abo.btScore} color="#2F5DE5" height={5} />
          </div>
          <div>
            <div className="flex items-center justify-between mb-1">
              <span className="text-[11px] font-medium text-ink-700">EM Pack Progress</span>
              <span className="text-[11px] num text-ink-500">{abo.emPack}/15</span>
            </div>
            <Bar value={abo.emPack} max={15} color="#F59E0B" height={5} />
          </div>
          <div>
            <div className="flex items-center justify-between mb-1">
              <span className="text-[11px] font-medium text-ink-700">Life Skill (Wheel)</span>
              <span className="text-[11px] num text-ink-500">{abo.lifeSkill.toFixed(1)} / 10</span>
            </div>
            <Bar value={abo.lifeSkill} max={10} color="#7C3AED" height={5} />
          </div>
        </div>

        {/* Actions */}
        <div className="grid grid-cols-3 gap-2 pt-2 border-t border-ink-100">
          <Btn variant="ghost" size="sm" icon={<Icon name="calendar" className="w-3.5 h-3.5" />}>ดูปฏิทิน</Btn>
          <Btn variant="ghost" size="sm" icon={<Icon name="line" className="w-3.5 h-3.5" />}>ส่ง LINE</Btn>
          <Btn variant="brand" size="sm" icon={<Icon name="sparkles" className="w-3.5 h-3.5" />}>โค้ชชิ่ง</Btn>
        </div>
      </div>
    </div>
  );
}

function OrgTree() {
  // Simple two-level org tree rendered as a column
  const me = { id: 'me', name: 'พิมพ์ชนก ศ.', pin: '18%', color: '#1B379F' };
  const directs = window.ABO_LIST.filter(a => a.upline === 'me');
  return (
    <Card title="โครงสร้างองค์กร · 2 ระดับ">
      <div className="overflow-x-auto scroll-thin">
        <div className="min-w-[700px]">
          {/* Me */}
          <div className="flex flex-col items-center">
            <NodeChip name={me.name} sub={me.pin} color={me.color} large />
            <div className="w-px h-6 bg-ink-200" />
          </div>
          {/* Directs */}
          <div className="relative">
            <div className="absolute top-0 left-[10%] right-[10%] h-px bg-ink-200" />
            <div className="grid gap-2" style={{ gridTemplateColumns: `repeat(${Math.max(directs.length, 1)}, minmax(0, 1fr))` }}>
              {directs.map(d => {
                const downlines = window.ABO_LIST.filter(a => a.upline === d.id);
                return (
                  <div key={d.id} className="flex flex-col items-center gap-2 pt-6 relative">
                    <div className="absolute top-0 left-1/2 w-px h-6 bg-ink-200" />
                    <NodeChip name={d.name} sub={`${d.pin} · ${d.ppv.toLocaleString()}PV`} color="#2F5DE5" />
                    {downlines.length > 0 && (
                      <div className="w-full pt-2 mt-2 border-t border-dashed border-ink-200">
                        <div className="text-[10px] text-ink-400 text-center mb-1.5 uppercase tracking-wider">{downlines.length} downlines</div>
                        <div className="flex flex-wrap justify-center gap-1.5">
                          {downlines.map(dl => (
                            <NodeChip key={dl.id} name={dl.name} sub={dl.pin} color="#94A3B8" small />
                          ))}
                        </div>
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </div>
    </Card>
  );
}

function NodeChip({ name, sub, color, large, small }) {
  const sz = large ? 'px-4 py-3' : small ? 'px-2 py-1' : 'px-3 py-2';
  return (
    <div className={`bg-white rounded-xl border ${large ? 'border-brand-200 shadow-card' : 'border-ink-100'} ${sz} flex items-center gap-2 text-center`}>
      <Avatar user={{ avatar: name.charAt(0), color }} size={large ? 32 : small ? 18 : 24} />
      <div className="min-w-0">
        <div className={`font-semibold text-ink-900 truncate ${large ? 'text-sm' : small ? 'text-[10px]' : 'text-xs'}`}>{name}</div>
        {!small && <div className="text-[10px] text-ink-500 num">{sub}</div>}
      </div>
    </div>
  );
}

function StudyProgress() {
  return (
    <Card title="ความคืบหน้าการเรียน EM Pack · ทั้งทีม">
      <div className="overflow-x-auto scroll-thin">
        <div className="min-w-[820px]">
          {/* Headers — pack numbers */}
          <div className="grid items-center gap-1 mb-2" style={{ gridTemplateColumns: '180px repeat(15, 1fr)' }}>
            <div className="text-[10px] uppercase tracking-wider font-semibold text-ink-400">DL Member</div>
            {Array.from({ length: 15 }, (_, i) => (
              <div key={i} className="text-[10px] text-center text-ink-400 font-semibold num">P{i}</div>
            ))}
          </div>
          {window.ABO_LIST.filter(a => a.active).map(a => (
            <div key={a.id} className="grid items-center gap-1 py-1.5 border-t border-ink-100" style={{ gridTemplateColumns: '180px repeat(15, 1fr)' }}>
              <div className="flex items-center gap-2 pr-2">
                <Avatar user={{ avatar: a.name.charAt(0), color: a.btScore >= 0.7 ? '#10B981' : '#2F5DE5' }} size={20} />
                <span className="text-xs font-medium text-ink-900 truncate">{a.name}</span>
              </div>
              {Array.from({ length: 15 }, (_, i) => {
                const done = i < a.emPack;
                return (
                  <div key={i} className={`aspect-square rounded ${done ? 'bg-brand-500' : 'bg-ink-100'} flex items-center justify-center`}>
                    {done && <Icon name="check" className="w-2.5 h-2.5 text-white" strokeWidth={3} />}
                  </div>
                );
              })}
            </div>
          ))}
        </div>
      </div>
      <div className="mt-4 pt-3 border-t border-ink-100 flex items-center gap-4 text-[11px] text-ink-500">
        <span className="flex items-center gap-1.5"><div className="w-2.5 h-2.5 bg-brand-500 rounded" />ฟังแล้ว</span>
        <span className="flex items-center gap-1.5"><div className="w-2.5 h-2.5 bg-ink-200 rounded" />ยังไม่ฟัง</span>
        <span className="ml-auto">เรียงตามชื่อ · 15 Packs ต่อคน</span>
      </div>
    </Card>
  );
}

window.AboView = AboView;
