// 6W Tracking — customer roster for weight-loss program (EM6W).

function SixWView() {
  const [selectedId, setSelectedId] = useState(window.CUSTOMERS_6W[0].id);
  const [filter, setFilter] = useState('all');

  const customers = window.CUSTOMERS_6W;
  const filtered = filter === 'all' ? customers : customers.filter(c => c.status === filter);
  const selected = customers.find(c => c.id === selectedId);

  const stats = {
    active: customers.filter(c => c.status === 'active').length,
    starting: customers.filter(c => c.status === 'starting').length,
    graduated: customers.filter(c => c.status === 'graduated').length,
    paused: customers.filter(c => c.status === 'paused').length,
    avgLoss: (customers.reduce((s, c) => s + (c.start - c.current), 0) / customers.length).toFixed(1),
  };

  return (
    <div className="space-y-5">
      <SectionHead
        eyebrow="Module · 6W Tracking"
        title="ข้อมูลลูกค้าลดน้ำหนัก"
        sub="รายชื่อลูกค้าในระบบ EM6W · ความคืบหน้า, ชุด BodyKey ที่ใช้, น้ำหนักรายสัปดาห์"
        right={
          <div className="flex items-center gap-2">
            <Btn variant="ghost" size="sm" icon={<Icon name="filter" />}>Filter</Btn>
            <Btn variant="brand" size="sm" icon={<Icon name="plus" />}>เพิ่มลูกค้า</Btn>
          </div>
        }
      />

      {/* Stats strip */}
      <div className="grid grid-cols-12 gap-4">
        <div className="col-span-12">
          <Card pad={false}>
            <div className="grid grid-cols-2 md:grid-cols-5 divide-x divide-ink-100">
              <div className="p-5">
                <Stat label="Active" value={stats.active} sub="cases" accent="#10B981" icon={<Icon name="fire" className="w-3.5 h-3.5" />} />
              </div>
              <div className="p-5">
                <Stat label="เริ่มต้น" value={stats.starting} sub="สัปดาห์ 1" accent="#2F5DE5" icon={<Icon name="spark" className="w-3.5 h-3.5" />} />
              </div>
              <div className="p-5">
                <Stat label="จบคอร์ส" value={stats.graduated} sub="สำเร็จ" accent="#7C3AED" icon={<Icon name="check" className="w-3.5 h-3.5" />} />
              </div>
              <div className="p-5">
                <Stat label="พัก" value={stats.paused} sub="ชั่วคราว" accent="#94A3B8" icon={<Icon name="clock" className="w-3.5 h-3.5" />} />
              </div>
              <div className="p-5">
                <Stat label="น้ำหนักลดเฉลี่ย" value={`-${stats.avgLoss}`} sub="kg / คน" accent="#EC4899" icon={<Icon name="weight" className="w-3.5 h-3.5" />} />
              </div>
            </div>
          </Card>
        </div>
      </div>

      {/* List + Detail layout */}
      <div className="grid grid-cols-12 gap-4">
        {/* Customer list */}
        <Card className="col-span-12 lg:col-span-5" pad={false}>
          <div className="px-5 pt-4 pb-3 flex items-center justify-between border-b border-ink-100">
            <div>
              <h3 className="text-sm font-semibold text-ink-800">รายชื่อลูกค้า</h3>
              <p className="text-[11px] text-ink-400">{filtered.length} ราย</p>
            </div>
            <div className="flex gap-1">
              {[
                { id: 'all',       label: 'ทั้งหมด' },
                { id: 'active',    label: 'Active'  },
                { id: 'starting',  label: 'เริ่ม'    },
                { id: 'graduated', label: 'จบ'      },
              ].map(f => (
                <button key={f.id} onClick={() => setFilter(f.id)}
                  className={`text-[11px] font-medium px-2 py-1 rounded-md transition-all ${filter === f.id ? 'bg-ink-900 text-white' : 'text-ink-500 hover:bg-ink-50'}`}>
                  {f.label}
                </button>
              ))}
            </div>
          </div>
          <div className="max-h-[600px] overflow-y-auto scroll-thin">
            <ul className="divide-y divide-ink-100">
              {filtered.map(c => {
                const loss = (c.start - c.current).toFixed(1);
                const progress = (c.start - c.current) / (c.start - c.goal);
                const isSelected = c.id === selectedId;
                return (
                  <li key={c.id}>
                    <button onClick={() => setSelectedId(c.id)}
                      className={`w-full px-5 py-3 text-left transition-all ${isSelected ? 'bg-emerald-50/60' : 'hover:bg-ink-50/50'}`}>
                      <div className="flex items-center gap-3">
                        <Avatar user={{ avatar: c.name.charAt(c.name.indexOf(' ')+1) || 'ค', color: ['#10B981','#2F5DE5','#8B5CF6','#EC4899','#F59E0B','#06B6D4'][c.id.charCodeAt(1)%6] }} size={36} />
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center gap-2">
                            <span className="text-sm font-semibold text-ink-900 truncate">{c.name}</span>
                            <CustomerStatusPill status={c.status} />
                          </div>
                          <div className="text-[11px] text-ink-500 flex items-center gap-2 mt-0.5">
                            <span className="num">W{c.week}/{c.weeks}</span>
                            <span className="text-ink-300">·</span>
                            <span className="num text-emerald-600 font-semibold">▼{loss} kg</span>
                            <span className="text-ink-300">·</span>
                            <span>อัปเดต {c.lastUpdate}</span>
                          </div>
                          <div className="mt-1.5"><Bar value={progress} color={progress >= 0.9 ? '#7C3AED' : progress >= 0.5 ? '#10B981' : '#F59E0B'} height={3} /></div>
                        </div>
                      </div>
                    </button>
                  </li>
                );
              })}
            </ul>
          </div>
        </Card>

        {/* Detail panel */}
        <div className="col-span-12 lg:col-span-7">
          {selected && <CustomerDetail customer={selected} />}
        </div>
      </div>
    </div>
  );
}

function CustomerStatusPill({ status }) {
  const map = {
    active:    { label: 'Active',  color: '#10B981', tint: '#E7F8F1' },
    starting:  { label: 'เริ่ม',    color: '#2F5DE5', tint: '#EEF4FF' },
    graduated: { label: 'จบคอร์ส', color: '#7C3AED', tint: '#F3EFFE' },
    paused:    { label: 'พัก',     color: '#94A3B8', tint: '#F1F5F9' },
  };
  const m = map[status];
  return <Pill color={m.color} tint={m.tint} size="xs">{m.label}</Pill>;
}

function CustomerDetail({ customer }) {
  const c = customer;
  const loss = c.start - c.current;
  const target = c.start - c.goal;
  const owner = window.TEAM.find(u => u.id === c.owner);

  // Synthesize weight log for this customer
  const log = Array.from({ length: c.week + 1 }, (_, i) => {
    const ratio = c.week > 0 ? i / c.week : 0;
    return { week: i, w: +(c.start - loss * ratio).toFixed(1) };
  });

  return (
    <div className="space-y-4">
      {/* Hero summary */}
      <Card className="bg-gradient-to-br from-emerald-50 to-white border-emerald-100">
        <div className="flex items-start gap-4">
          <Avatar user={{ avatar: c.name.charAt(c.name.indexOf(' ')+1) || 'ค', color: '#10B981' }} size={56} />
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2">
              <h2 className="text-lg font-semibold text-ink-900">{c.name}</h2>
              <CustomerStatusPill status={c.status} />
            </div>
            <div className="text-[11px] text-ink-500 mt-0.5">EM6W · Week {c.week}/{c.weeks} · {owner && `ดูแลโดย ${owner.name}`}</div>
          </div>
          <div className="text-right">
            <div className="text-[10px] uppercase tracking-wider text-emerald-700/70 font-semibold">ลดสะสม</div>
            <div className="flex items-baseline justify-end gap-1">
              <span className="text-3xl font-semibold num text-emerald-700">▼{loss.toFixed(1)}</span>
              <span className="text-sm text-emerald-600/70 num">kg</span>
            </div>
            <div className="text-[11px] text-ink-500 num">{Math.round(loss / target * 100)}% สำเร็จ</div>
          </div>
        </div>
        <div className="mt-3 grid grid-cols-3 gap-3 text-center">
          <div className="bg-white rounded-lg p-2 border border-emerald-100">
            <div className="text-[10px] text-ink-400 uppercase tracking-wider">เริ่ม</div>
            <div className="text-base font-semibold num text-ink-900">{c.start} kg</div>
          </div>
          <div className="bg-white rounded-lg p-2 border border-emerald-200">
            <div className="text-[10px] text-ink-400 uppercase tracking-wider">ปัจจุบัน</div>
            <div className="text-base font-semibold num text-emerald-600">{c.current} kg</div>
          </div>
          <div className="bg-white rounded-lg p-2 border border-emerald-100">
            <div className="text-[10px] text-ink-400 uppercase tracking-wider">เป้าหมาย</div>
            <div className="text-base font-semibold num text-ink-900">{c.goal} kg</div>
          </div>
        </div>
      </Card>

      {/* Chart */}
      <Card title="กราฟน้ำหนักรายสัปดาห์">
        <SimpleWeightChart log={log} goal={c.goal} />
      </Card>

      <div className="grid grid-cols-2 gap-4">
        <Card title="ชุด BodyKey">
          <div className="space-y-2">
            {(c.bodykey.length === 0 ? ['—'] : c.bodykey).map((b, i) => (
              <div key={i} className="flex items-center gap-2 p-2 rounded-lg bg-emerald-50/40 border border-emerald-100">
                <span className="text-base">🥤</span>
                <span className="text-xs font-medium text-ink-700">{b}</span>
              </div>
            ))}
          </div>
        </Card>
        <Card title="โน้ต">
          <div className="text-xs text-ink-700 leading-relaxed">{c.note}</div>
          <div className="mt-3 pt-3 border-t border-ink-100">
            <Btn variant="brand" size="sm" icon={<Icon name="plus" className="w-3.5 h-3.5" />}>บันทึกน้ำหนักสัปดาห์นี้</Btn>
          </div>
        </Card>
      </div>
    </div>
  );
}

function SimpleWeightChart({ log, goal }) {
  if (log.length < 2) {
    return <div className="text-center py-8 text-xs text-ink-400">ยังไม่มีข้อมูลพอวาดกราฟ</div>;
  }
  const w = 640, h = 200, padL = 32, padR = 12, padT = 12, padB = 24;
  const ys = log.map(d => d.w);
  const min = Math.min(...ys, goal) - 1;
  const max = Math.max(...ys) + 1;
  const xScale = (v) => padL + (v / (log.length - 1)) * (w - padL - padR);
  const yScale = (v) => padT + (1 - (v - min) / (max - min)) * (h - padT - padB);
  const pts = log.map((d, i) => [xScale(i), yScale(d.w)]);
  const path = pts.map((p, i) => (i === 0 ? `M ${p[0]} ${p[1]}` : `L ${p[0]} ${p[1]}`)).join(' ');
  const area = `${path} L ${pts[pts.length-1][0]} ${h - padB} L ${pts[0][0]} ${h - padB} Z`;

  return (
    <svg viewBox={`0 0 ${w} ${h}`} className="w-full">
      <defs>
        <linearGradient id="grd6w" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor="#10B981" stopOpacity="0.32" />
          <stop offset="100%" stopColor="#10B981" stopOpacity="0" />
        </linearGradient>
      </defs>
      <line x1={padL} y1={yScale(goal)} x2={w - padR} y2={yScale(goal)} stroke="#94A3B8" strokeWidth="1.5" strokeDasharray="6 4" />
      <text x={w - padR - 4} y={yScale(goal) - 4} textAnchor="end" fontSize="10" fill="#64748B" fontWeight="600">เป้า {goal}kg</text>
      <path d={area} fill="url(#grd6w)" />
      <path d={path} stroke="#10B981" strokeWidth="2.5" fill="none" strokeLinecap="round" strokeLinejoin="round" />
      {pts.map((p, i) => (
        <g key={i}>
          <circle cx={p[0]} cy={p[1]} r="4.5" fill="white" stroke="#10B981" strokeWidth="2.5" />
          <text x={p[0]} y={p[1] - 10} textAnchor="middle" fontSize="10" fill="#0F1E38" fontWeight="600" className="num">{log[i].w}</text>
        </g>
      ))}
      {log.map((d, i) => (
        <text key={i} x={xScale(i)} y={h - 8} textAnchor="middle" fontSize="10" fill="#9DAAC4" fontWeight="600">W{d.week}</text>
      ))}
    </svg>
  );
}

window.SixWView = SixWView;
