// 6W Tracking — photos, status, reminders (split from 6w.jsx).
// BodyPhotosCard, PhotoLightbox, StatusChangeBar, ReminderCard, DatePicker.

// ============== Body Photos ==============
function SixWBodyPhotosCard({ customer, onUpdate }) {
  const [activeWeek, setActiveWeek] = useState('Before');
  const [lightbox, setLightbox] = useState(null);
  const photos = customer.photos || {};

  const setPhoto = (week, dirId, dataUrl) => {
    const wp = photos[week] || {};
    onUpdate({ photos: { ...photos, [week]: { ...wp, [dirId]: dataUrl, _ts: Date.now() } } });
  };
  const removePhoto = (week, dirId) => {
    const wp = { ...(photos[week] || {}) }; delete wp[dirId];
    onUpdate({ photos: { ...photos, [week]: wp } });
  };
  const countWeekPhotos = (w) => {
    const wp = photos[w] || {};
    return SIXW_PHOTO_DIRECTIONS.filter(d => wp[d.id]).length;
  };
  const totalPhotos = SIXW_PHOTO_WEEKS.reduce((s, w) => s + countWeekPhotos(w), 0);

  return (
    <Card pad={false}>
      <div className="px-4 py-2.5 border-b border-ink-100 flex items-center justify-between bg-gradient-to-r from-pink-50 to-white">
        <h3 className="text-sm font-extrabold tracking-wide text-pink-700 flex items-center gap-1.5">
          <SixWBodyIcon className="w-4 h-4" />
          รูปถ่ายร่างกาย · 4 ด้าน × สัปดาห์
        </h3>
        <span className="text-[10px] text-ink-400 num">{totalPhotos} รูป</span>
      </div>

      <div className="px-3 py-2.5 border-b border-ink-100 flex items-center gap-1 overflow-x-auto scroll-thin">
        {SIXW_PHOTO_WEEKS.map(w => {
          const count = countWeekPhotos(w);
          const isActive = w === activeWeek;
          const complete = count === 4;
          return (
            <button key={w} onClick={() => setActiveWeek(w)}
              className={`flex-shrink-0 px-3 py-1.5 rounded-md text-[11px] font-semibold border transition-all ${isActive ? 'border-transparent bg-pink-500 text-white' : 'bg-white border-ink-200 text-ink-600 hover:border-ink-300'}`}>
              <span>{w}</span>
              {count > 0 && (
                <span className={`ml-1.5 text-[9px] num ${isActive ? 'text-white/80' : complete ? 'text-emerald-600' : 'text-ink-400'}`}>
                  {count}/4{complete ? ' ✓' : ''}
                </span>
              )}
            </button>
          );
        })}
      </div>

      <div className="p-3 grid grid-cols-2 sm:grid-cols-4 gap-2">
        {SIXW_PHOTO_DIRECTIONS.map(d => {
          const url = photos[activeWeek]?.[d.id];
          return (
            <SixWPhotoSlot key={d.id}
              direction={d} url={url} week={activeWeek}
              onUpload={(dataUrl) => setPhoto(activeWeek, d.id, dataUrl)}
              onRemove={() => removePhoto(activeWeek, d.id)}
              onPreview={() => url && setLightbox({ week: activeWeek, dir: d, url })}
            />
          );
        })}
      </div>

      {lightbox && (
        <SixWPhotoLightbox customer={customer} photos={photos} initial={lightbox} onClose={() => setLightbox(null)} />
      )}
    </Card>
  );
}

function SixWPhotoSlot({ direction, url, week, onUpload, onRemove, onPreview }) {
  const fileRef = useRef(null);
  const handleFile = (file) => {
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (e) => onUpload(e.target.result);
    reader.readAsDataURL(file);
  };

  if (url) {
    return (
      <div className="relative group rounded-lg overflow-hidden aspect-[3/4] bg-ink-100 border border-ink-200">
        <img src={url} alt={direction.label} className="w-full h-full object-cover cursor-pointer" onClick={onPreview} />
        <div className="absolute top-1 left-1 px-1.5 py-0.5 rounded bg-black/60 backdrop-blur text-[9px] font-bold text-white">{direction.label}</div>
        <button onClick={onPreview} className="absolute inset-0 bg-black/0 hover:bg-black/30 transition-colors flex items-center justify-center">
          <div className="opacity-0 group-hover:opacity-100 transition-opacity">
            <div className="bg-white/90 backdrop-blur rounded-full p-2">
              <Icon name="search" className="w-4 h-4 text-ink-900" />
            </div>
          </div>
        </button>
        <div className="absolute top-1 right-1 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
          <button onClick={(e) => { e.stopPropagation(); fileRef.current?.click(); }} title="เปลี่ยนรูป"
            className="w-6 h-6 rounded-md bg-white/90 backdrop-blur text-ink-700 hover:bg-white flex items-center justify-center">
            <SixWUploadCameraIcon className="w-3 h-3" />
          </button>
          <button onClick={(e) => { e.stopPropagation(); if (confirm('ลบรูปนี้?')) onRemove(); }} title="ลบรูป"
            className="w-6 h-6 rounded-md bg-white/90 backdrop-blur text-rose-500 hover:bg-white flex items-center justify-center">
            <Icon name="x" className="w-3 h-3" strokeWidth={2.5} />
          </button>
        </div>
        <input ref={fileRef} type="file" accept="image/*" className="hidden"
          onChange={e => { handleFile(e.target.files?.[0]); e.target.value = ''; }} />
      </div>
    );
  }

  return (
    <button onClick={() => fileRef.current?.click()}
      onDragOver={e => e.preventDefault()}
      onDrop={e => { e.preventDefault(); handleFile(e.dataTransfer.files?.[0]); }}
      className="aspect-[3/4] rounded-lg border-2 border-dashed border-pink-200 hover:border-pink-400 hover:bg-pink-50/50 transition-all flex flex-col items-center justify-center gap-1.5 group">
      <div className="w-10 h-10 rounded-full bg-pink-100 group-hover:bg-pink-200 flex items-center justify-center transition-colors">
        <SixWDirectionIcon id={direction.id} className="w-6 h-6 text-pink-500" />
      </div>
      <div className="text-center">
        <div className="text-xs font-semibold text-ink-900">{direction.label}</div>
        <div className="text-[9px] text-ink-400">{direction.subtitle} · คลิกอัปโหลด</div>
      </div>
      <input ref={fileRef} type="file" accept="image/*" className="hidden"
        onChange={e => { handleFile(e.target.files?.[0]); e.target.value = ''; }} />
    </button>
  );
}

function SixWPhotoLightbox({ customer, photos, initial, onClose }) {
  const [week, setWeek] = useState(initial.week);
  const [dir, setDir] = useState(initial.dir);
  const url = photos[week]?.[dir.id];

  useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'Escape') onClose();
      if (e.key === 'ArrowRight') {
        const i = SIXW_PHOTO_DIRECTIONS.findIndex(d => d.id === dir.id);
        if (i < SIXW_PHOTO_DIRECTIONS.length - 1) setDir(SIXW_PHOTO_DIRECTIONS[i + 1]);
      }
      if (e.key === 'ArrowLeft') {
        const i = SIXW_PHOTO_DIRECTIONS.findIndex(d => d.id === dir.id);
        if (i > 0) setDir(SIXW_PHOTO_DIRECTIONS[i - 1]);
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [dir]);

  return (
    <div className="fixed inset-0 z-50 bg-black/85 backdrop-blur-sm flex flex-col" onClick={onClose}>
      <div className="px-5 py-3 flex items-center justify-between text-white flex-shrink-0" onClick={e => e.stopPropagation()}>
        <div>
          <div className="text-sm font-semibold">{customer.name} · {dir.label} ({dir.subtitle})</div>
          <div className="text-[11px] text-white/60 num">{week}</div>
        </div>
        <div className="flex items-center gap-2">
          <span className="text-[11px] text-white/60">← → keyboard</span>
          <button onClick={onClose} className="w-8 h-8 rounded-lg bg-white/10 hover:bg-white/20 flex items-center justify-center">
            <Icon name="x" className="w-4 h-4" />
          </button>
        </div>
      </div>
      <div className="flex-1 flex items-center justify-center p-4 min-h-0" onClick={e => e.stopPropagation()}>
        {url
          ? <img src={url} alt="" className="max-w-full max-h-full object-contain rounded-lg" />
          : <div className="text-white/60 text-sm">ไม่มีรูปสำหรับ {week} · {dir.label}</div>}
      </div>
      <div className="flex-shrink-0 bg-black/30 backdrop-blur p-3" onClick={e => e.stopPropagation()}>
        <div className="flex items-center justify-center gap-1.5 mb-2">
          {SIXW_PHOTO_DIRECTIONS.map(d => {
            const has = !!photos[week]?.[d.id];
            return (
              <button key={d.id} onClick={() => setDir(d)} disabled={!has}
                className={`px-3 py-1.5 rounded-md text-[11px] font-semibold transition-all ${dir.id === d.id ? 'bg-white text-ink-900' : has ? 'bg-white/10 text-white hover:bg-white/20' : 'bg-white/5 text-white/30 cursor-not-allowed'}`}>
                {d.label}
              </button>
            );
          })}
        </div>
        <div className="flex items-center justify-center gap-1 overflow-x-auto">
          {SIXW_PHOTO_WEEKS.map(w => {
            const wp = photos[w] || {};
            const has = !!wp[dir.id];
            return (
              <button key={w} onClick={() => setWeek(w)} disabled={!has}
                className={`flex-shrink-0 w-10 aspect-[3/4] rounded overflow-hidden border-2 transition-all ${w === week ? 'border-white' : has ? 'border-white/30 hover:border-white/60' : 'border-white/10 opacity-30'}`}>
                {has ? <img src={wp[dir.id]} alt={w} className="w-full h-full object-cover" />
                     : <div className="w-full h-full bg-white/5 flex items-center justify-center text-[9px] text-white/40 font-bold">{w}</div>}
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function SixWBodyIcon({ className = 'w-4 h-4' }) {
  return (
    <svg viewBox="0 0 24 24" fill="currentColor" className={className}>
      <circle cx="12" cy="5" r="2.5" />
      <path d="M9 9h6l1.5 8h-2l-.5-5h-.5v8h-1.5v-5h-1v5h-1.5v-8h-.5l-.5 5h-2l1.5-8z" />
    </svg>
  );
}

function SixWDirectionIcon({ id, className = 'w-5 h-5' }) {
  if (id === 'front') return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className={className}>
      <circle cx="12" cy="5" r="2.5" fill="currentColor" stroke="none" />
      <circle cx="10.7" cy="4.7" r="0.4" fill="white" />
      <circle cx="13.3" cy="4.7" r="0.4" fill="white" />
      <path d="M7 10c0-.5.5-1 1-1h8c.5 0 1 .5 1 1l-1 7h-2l-.3-4h-.4v6h-2v-4h-.6v4h-2l-.3-6h-.4l-.3 4h-2L7 10z" fill="currentColor" stroke="none" />
    </svg>
  );
  if (id === 'side') return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className={className}>
      <path d="M14 3.5c1.5 0 2.5 1.2 2.5 2.5 0 .8-.3 1.5-.8 2L17 9l-1.5.3c-.5.4-1.2.7-2 .7-1 0-1.7-.3-2.2-.8" fill="currentColor" stroke="none" />
      <circle cx="14.5" cy="5.5" r="0.4" fill="white" />
      <path d="M11 10h3l1.5 6.5-1 .5-1-3v6h-2v-6l-1 3-1-.5L11 10z" fill="currentColor" stroke="none" />
    </svg>
  );
  if (id === 'back') return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className={className}>
      <circle cx="12" cy="5" r="2.5" fill="currentColor" stroke="none" />
      <path d="M7 10c0-.5.5-1 1-1h8c.5 0 1 .5 1 1l-1 7h-2l-.3-4h-.4v6h-2v-4h-.6v4h-2l-.3-6h-.4l-.3 4h-2L7 10z" fill="currentColor" stroke="none" opacity="0.5" />
      <line x1="12" y1="10" x2="12" y2="16" stroke="white" strokeWidth="0.6" />
      <line x1="9" y1="11" x2="15" y2="11" stroke="white" strokeWidth="0.4" />
    </svg>
  );
  if (id === 'angle') return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className={className}>
      <ellipse cx="12" cy="5" rx="2.3" ry="2.6" fill="currentColor" stroke="none" />
      <circle cx="11" cy="4.7" r="0.35" fill="white" />
      <circle cx="13" cy="5" r="0.35" fill="white" />
      <path d="M14 7l1 .5" stroke="currentColor" strokeWidth="0.6" />
      <path d="M8 10c0-.5.5-1 1-1h7c.5 0 1 .5 1 1l-1.5 7h-2l-.3-4h-.4v6h-2v-4h-.6v4h-2l-.3-6h-.4l-.3 4H7L8 10z" fill="currentColor" stroke="none" />
    </svg>
  );
  return null;
}

// ============== Status Change Bar ==============
function SixWStatusChangeBar({ customer, currentStatus, onChange }) {
  const ev = _sixwEvaluateProgress(customer);
  const options = [
    { id: 'active',    label: 'Active',    color: '#10B981', tint: '#E7F8F1', icon: 'fire',  desc: 'กำลังลดน้ำหนัก' },
    { id: 'graduated', label: 'จบ 6W',     color: '#7C3AED', tint: '#F3EFFE', icon: 'check', desc: 'จบคอร์ส 6 สัปดาห์' },
    { id: 'inactive',  label: 'ไม่ Active', color: '#94A3B8', tint: '#F1F5F9', icon: 'x',     desc: 'หยุดคอร์ส / ไม่ตอบกลับ' },
  ];
  const cur = options.find(o => o.id === currentStatus) || options[0];

  return (
    <Card pad={false} className="border-ink-200">
      <div className="px-4 py-3 flex items-center gap-3 flex-wrap">
        <div className="flex items-center gap-2 flex-shrink-0">
          <div className="w-7 h-7 rounded-md flex items-center justify-center text-white" style={{ background: cur.color }}>
            <Icon name={cur.icon} className="w-3.5 h-3.5" strokeWidth={2.5} />
          </div>
          <div className="leading-tight">
            <div className="text-[10px] uppercase tracking-wider text-ink-400 font-semibold">สถานะ</div>
            <div className="text-sm font-semibold text-ink-900">{cur.label}</div>
          </div>
        </div>
        <div className="w-px h-8 bg-ink-100 mx-1 hidden sm:block" />
        <div className="flex items-center gap-1.5">
          <span className="text-[11px] text-ink-500">เปลี่ยนเป็น:</span>
          {options.filter(o => o.id !== currentStatus).map(o => (
            <button key={o.id} onClick={() => {
              if (o.id !== 'active' && !confirm(`ย้าย "${customer.name}" ไปกลุ่ม "${o.label}" ใช่หรือไม่?`)) return;
              onChange(o.id);
            }}
              className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-[11px] font-semibold border transition-all hover:shadow-card"
              style={{ background: o.tint, color: o.color, borderColor: o.color + '40' }}>
              <Icon name={o.icon} className="w-3 h-3" strokeWidth={2.5} /> {o.label}
            </button>
          ))}
        </div>
        <div className="flex-1" />
        {currentStatus === 'active' && ev.weeksSince >= 6 && (
          <button onClick={() => onChange('graduated')}
            className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[11px] font-bold text-white bg-gradient-to-r from-purple-500 to-purple-600 shadow-md shadow-purple-500/30 hover:shadow-lg transition-all">
            <Icon name="sparkles" className="w-3 h-3" strokeWidth={2.5} />
            ✨ เกณฑ์จบคอร์สแล้ว — ติ๊ก "จบ 6W"
          </button>
        )}
        {currentStatus === 'active' && ev.daysSinceLastEntry !== null && ev.daysSinceLastEntry > 21 && (
          <button onClick={() => { if (confirm(`ย้าย "${customer.name}" ไปไม่ Active?`)) onChange('inactive'); }}
            className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[11px] font-bold text-white bg-slate-500 hover:bg-slate-600 transition-all">
            ⚠ เงียบไป {ev.daysSinceLastEntry} วัน
          </button>
        )}
      </div>
    </Card>
  );
}

// ============== Progress evaluation + Reminders ==============
function _sixwEvaluateProgress(customer) {
  if (!customer) return { weeksSince: 0, lostKg: 0, expectedLoss: 0, status: 'on-track', daysSinceLastEntry: null, lastDate: null, nextFollowUpDate: null, needsDetox: false, needsFollowUp: false };
  const em = customer.em6w || {};
  const before = em.Before;
  const baseline = parseFloat(before?.uu);
  const weekOrder = ['Before','W1','W2','W3','W4','W5','W6','W7','W8','W9','W10','W11','W12','W13'];
  let lastWeekIdx = -1, lastDate = null, lastWeight = NaN;
  for (let i = weekOrder.length - 1; i >= 0; i--) {
    const w = em[weekOrder[i]] || customer.em13w?.[weekOrder[i]];
    if (w?.uu) {
      lastWeekIdx = i;
      lastWeight = parseFloat(w.uu);
      lastDate = _sixwParseThaiDate(w.date);
      break;
    }
  }
  const lostKg = (baseline && !isNaN(lastWeight)) ? (baseline - lastWeight) : 0;
  const weeksSince = lastWeekIdx;
  const expectedLoss = Math.max(0, weeksSince * 0.8);
  const slowLoss = weeksSince >= 2 && lostKg < expectedLoss * 0.5;
  const stagnant = weeksSince >= 2 && lostKg < 0.3 * weeksSince;
  const needsDetox = slowLoss || stagnant;
  let daysSinceLastEntry = null, needsFollowUp = false, nextFollowUpDate = null;
  if (lastDate) {
    daysSinceLastEntry = Math.floor((new Date() - lastDate) / 86400000);
    const next = new Date(lastDate); next.setDate(next.getDate() + 7);
    nextFollowUpDate = next;
    needsFollowUp = daysSinceLastEntry >= 7 && weeksSince >= 0 && weeksSince < 6;
  }
  let status = 'on-track';
  if (needsDetox) status = 'slow';
  else if (lostKg >= expectedLoss * 0.9) status = 'great';
  return { weeksSince: Math.max(0, weeksSince), lostKg, expectedLoss, status, daysSinceLastEntry, lastDate, nextFollowUpDate, needsDetox, needsFollowUp };
}

function SixWReminderCard({ customer }) {
  const ev = _sixwEvaluateProgress(customer);

  if (!ev.needsDetox && !ev.needsFollowUp) {
    if (ev.weeksSince === 0) return null;
    return (
      <Card className="bg-emerald-50/40 border-emerald-100">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 rounded-lg bg-emerald-500 text-white flex items-center justify-center flex-shrink-0">
            <Icon name="check" className="w-5 h-5" strokeWidth={2.5} />
          </div>
          <div className="flex-1">
            <div className="text-sm font-semibold text-emerald-800">{customer.name} กำลังไปได้ดี 🎉</div>
            <div className="text-[11px] text-emerald-700/70">
              สัปดาห์ที่ {ev.weeksSince} · ลดสะสม <span className="font-semibold num">{ev.lostKg.toFixed(1)} kg</span>
              {ev.expectedLoss > 0 && <> · เป้าหมาย ~{ev.expectedLoss.toFixed(1)} kg</>}
            </div>
          </div>
          <Pill color="#10B981" tint="white">on track</Pill>
        </div>
      </Card>
    );
  }

  return (
    <div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
      {ev.needsDetox && (
        <Card pad={false} className="border-rose-300 bg-gradient-to-br from-rose-50 to-white shadow-card">
          <div className="p-4">
            <div className="flex items-start gap-3">
              <div className="w-11 h-11 rounded-xl bg-rose-500 text-white flex items-center justify-center flex-shrink-0 shadow-lg shadow-rose-500/30">
                <SixWDetoxIcon className="w-6 h-6" />
              </div>
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-1.5 mb-1">
                  <span className="text-[10px] font-bold uppercase tracking-wider text-rose-600">⚠ น้ำหนักลงช้า</span>
                  <Pill color="#EF4444" tint="#FEE2E2" size="xs">นัด DETOX</Pill>
                </div>
                <div className="text-sm font-semibold text-ink-900 mb-1">{customer.name}</div>
                <div className="text-[11px] text-ink-600 leading-relaxed">
                  สัปดาห์ที่ {ev.weeksSince} ลดได้ <span className="font-bold text-rose-600 num">{ev.lostKg.toFixed(1)} kg</span> เทียบกับเป้าหมาย <span className="font-bold num">~{ev.expectedLoss.toFixed(1)} kg</span> · ต่ำกว่า 50%
                </div>
                <div className="mt-2.5 p-2.5 rounded-lg bg-white border border-rose-200/60">
                  <div className="text-[10px] font-semibold text-rose-700 mb-1">💡 แนะนำให้คุย</div>
                  <ul className="text-[11px] text-ink-700 space-y-0.5 leading-relaxed">
                    <li>· ทบทวนเมนูอาหาร 3 มื้อ ที่ผ่านมา</li>
                    <li>· เพิ่มชุด <span className="font-semibold">DETOX</span> (Phytopowder + Nutrilite Fiber)</li>
                    <li>· ตรวจการนอน + ความเครียด</li>
                  </ul>
                </div>
                <div className="mt-2.5 flex items-center gap-2">
                  <Btn variant="brand" size="sm" icon={<Icon name="calendar" className="w-3.5 h-3.5" />}>นัดคุย DETOX</Btn>
                  <button className="text-[11px] font-medium text-ink-500 hover:text-ink-900">เลื่อนเตือน</button>
                </div>
              </div>
            </div>
          </div>
        </Card>
      )}
      {ev.needsFollowUp && (
        <Card pad={false} className="border-amber-300 bg-gradient-to-br from-amber-50 to-white shadow-card">
          <div className="p-4">
            <div className="flex items-start gap-3">
              <div className="w-11 h-11 rounded-xl bg-amber-500 text-white flex items-center justify-center flex-shrink-0 shadow-lg shadow-amber-500/30">
                <Icon name="bell" className="w-5 h-5" strokeWidth={2} />
              </div>
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-1.5 mb-1">
                  <span className="text-[10px] font-bold uppercase tracking-wider text-amber-700">⏰ ครบรอบ Follow-up</span>
                  <Pill color="#F59E0B" tint="#FEF3C7" size="xs">นัดชั่ง W{ev.weeksSince + 1}</Pill>
                </div>
                <div className="text-sm font-semibold text-ink-900 mb-1">{customer.name}</div>
                <div className="text-[11px] text-ink-600 leading-relaxed">
                  ผ่านมา <span className="font-bold text-amber-700 num">{ev.daysSinceLastEntry} วัน</span> จากนัดล่าสุด ({_sixwFormatThaiDate(ev.lastDate)})
                  {ev.daysSinceLastEntry >= 10 && <span className="text-rose-600 font-semibold"> · เลยกำหนด</span>}
                </div>
                <div className="mt-2.5 p-2.5 rounded-lg bg-white border border-amber-200/60">
                  <div className="text-[10px] font-semibold text-amber-700 mb-1">📋 สิ่งที่ต้องทำ</div>
                  <ul className="text-[11px] text-ink-700 space-y-0.5 leading-relaxed">
                    <li>· นัดชั่งน้ำหนัก W{ev.weeksSince + 1} ของ {customer.name}</li>
                    <li>· เทียบดูค่ารอบเอว / %Fat / VFat</li>
                    <li>· อัปเดต Google Slides สรุปสัปดาห์</li>
                  </ul>
                </div>
                <div className="mt-2.5 flex items-center gap-2">
                  <Btn variant="gold" size="sm" icon={<Icon name="calendar" className="w-3.5 h-3.5" />}>นัด F/U สัปดาห์นี้</Btn>
                  <button className="text-[11px] font-medium text-ink-500 hover:text-ink-900">ส่ง LINE เตือน</button>
                </div>
              </div>
            </div>
          </div>
        </Card>
      )}
    </div>
  );
}

function SixWDetoxIcon({ className = 'w-5 h-5' }) {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" className={className}>
      <path d="M8 3h8l-1 4a4 4 0 0 1 3 4v5a5 5 0 0 1-5 5h-2a5 5 0 0 1-5-5v-5a4 4 0 0 1 3-4l-1-4z" />
      <path d="M10 13.5c.5-.5 1-1 2-1s1.5.5 2 1" />
      <circle cx="9" cy="16" r="0.5" fill="currentColor" />
      <circle cx="13" cy="17" r="0.5" fill="currentColor" />
      <circle cx="15" cy="15" r="0.5" fill="currentColor" />
    </svg>
  );
}

// ============== Date picker ==============
function SixWDatePickerInput({ value, onChange, tone = '#10B981', className = '', style = {} }) {
  const inputRef = useRef(null);
  return (
    <div className={`relative ${className}`}>
      <input type="text" readOnly value={value || ''} placeholder="วัน/เดือน/ปี (พ.ศ.)"
        onClick={() => inputRef.current?.showPicker?.() || inputRef.current?.click()}
        className="w-full h-9 pl-3 pr-9 text-sm num border rounded-lg outline-none focus:ring-2 bg-white cursor-pointer"
        style={{ '--tw-ring-color': tone + '40', borderColor: value ? tone + '80' : '#C9D2E3', ...style }} />
      <button type="button"
        onClick={() => inputRef.current?.showPicker?.() || inputRef.current?.click()}
        className="absolute right-2 top-1/2 -translate-y-1/2 w-6 h-6 rounded-md flex items-center justify-center text-ink-400 hover:text-ink-900 hover:bg-ink-100" tabIndex={-1}>
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="w-3.5 h-3.5">
          <rect x="3" y="5" width="18" height="16" rx="2" />
          <path d="M3 9h18M8 3v4M16 3v4" />
        </svg>
      </button>
      <input ref={inputRef} type="date" value={_sixwThaiDateToInput(value)}
        onChange={e => {
          const v = e.target.value;
          if (!v) { onChange(''); return; }
          const [y, m, d] = v.split('-').map(Number);
          onChange(_sixwFormatThaiDate(new Date(y, m - 1, d)));
        }}
        className="absolute left-0 top-0 opacity-0 w-full h-9 pointer-events-none"
        style={{ colorScheme: 'light' }} />
    </div>
  );
}
