// 6W Tracking — customer cards (split from 6w.jsx).
// AddCustomerModal, Banner, ProgressHero, info/slides cards.

// ============== Add customer modal ==============
function SixWAddCustomerModal({ onClose, onCreate }) {
  const [name, setName] = useState('');
  const [abo, setAbo] = useState('');
  const [startDate, setStartDate] = useState(_sixwFormatThaiDate(new Date()));
  const [startWeight, setStartWeight] = useState('');
  const [goalWeight, setGoalWeight] = useState('');
  const [height, setHeight] = useState('');
  const [autoCreateSlide, setAutoCreateSlide] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [step, setStep] = useState(0);

  const canSubmit = name.trim().length > 0 && abo.length === 10;

  const submit = async () => {
    if (!canSubmit) return;
    setSubmitting(true);
    let slideUrl = '';
    if (autoCreateSlide) {
      const labels = [
        'บันทึกข้อมูลลูกค้า',
        'สร้าง Google Slides จาก template',
        'แทนที่ชื่อ + ABO ในสไลด์',
        'ตั้งค่า share ลิงก์',
      ];
      for (let i = 0; i < labels.length; i++) {
        await new Promise(r => setTimeout(r, 450));
        setStep(i + 1);
      }
      // Generate a plausible-looking fake URL
      const fakeId = '1' + Array.from({length: 43}, () =>
        'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_'
          .charAt(Math.floor(Math.random() * 64))
      ).join('');
      slideUrl = `https://docs.google.com/presentation/d/${fakeId}/edit?usp=sharing`;
    } else {
      await new Promise(r => setTimeout(r, 300));
    }
    await onCreate({
      name: name.trim(), abo,
      startDate,
      startWeight: parseFloat(startWeight) || 0,
      goalWeight: parseFloat(goalWeight) || 0,
      height: parseFloat(height) || 0,
      checkupSlide: slideUrl,
    });
  };

  return (
    <Modal open={true} onClose={submitting ? undefined : onClose} size="md"
      title={
        <div className="flex items-center gap-2">
          <div className="w-7 h-7 rounded-md flex items-center justify-center text-white" style={{ background: '#10B981' }}>
            <Icon name="plus" className="w-4 h-4" strokeWidth={2.5} />
          </div>
          <div>
            <div className="text-sm font-semibold text-ink-900">เพิ่มลูกค้าลดน้ำหนัก</div>
            <div className="text-[10px] text-ink-400 uppercase tracking-wider font-semibold">EM6W · New Customer</div>
          </div>
        </div>
      }
      footer={
        !submitting && (
          <div className="flex items-center justify-between">
            <span className="text-[11px] text-ink-400">ABO ต้อง 10 หลัก</span>
            <div className="flex items-center gap-2">
              <Btn variant="ghost" size="sm" onClick={onClose}>ยกเลิก</Btn>
              <Btn variant="brand" size="sm" icon={<Icon name="check" className="w-3.5 h-3.5" />} onClick={submit} disabled={!canSubmit}>
                {autoCreateSlide ? 'สร้าง + Slide' : 'สร้างลูกค้า'}
              </Btn>
            </div>
          </div>
        )
      }>
      {submitting ? (
        <div className="py-2 space-y-2.5">
          {['บันทึกข้อมูลลูกค้า','สร้าง Google Slides จาก template','แทนที่ชื่อ + ABO ในสไลด์','ตั้งค่า share ลิงก์'].slice(0, autoCreateSlide ? 4 : 1).map((s, i) => {
            const done = i < step;
            const isActive = i === step;
            return (
              <div key={i} className="flex items-center gap-3 text-xs">
                <div className={`w-5 h-5 rounded-full flex items-center justify-center flex-shrink-0 ${done ? 'bg-emerald-500' : isActive ? 'bg-amber-400 animate-pulse' : 'bg-ink-200'}`}>
                  {done && <Icon name="check" className="w-3 h-3 text-white" strokeWidth={3} />}
                </div>
                <span className={done ? 'text-ink-700' : isActive ? 'text-ink-900 font-semibold' : 'text-ink-400'}>{s}</span>
              </div>
            );
          })}
        </div>
      ) : (
        <div className="space-y-3">
          <div className="grid grid-cols-12 gap-3">
            <div className="col-span-12">
              <label className="text-[10px] uppercase tracking-wider text-ink-500 font-semibold block mb-1.5">ชื่อลูกค้า *</label>
              <input value={name} onChange={e => setName(e.target.value)} autoFocus
                placeholder="เช่น คุณนภัสสร พ."
                className="w-full h-9 px-3 text-sm border border-ink-200 rounded-lg outline-none focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500/20 bg-white" />
            </div>
            <div className="col-span-7">
              <label className="text-[10px] uppercase tracking-wider text-ink-500 font-semibold block mb-1.5">ABO * (10 หลัก)</label>
              <input value={abo} onChange={e => setAbo(e.target.value.replace(/\D/g, '').slice(0, 10))}
                placeholder="9201853042"
                className={`w-full h-9 px-3 text-sm num border rounded-lg outline-none focus:ring-2 bg-white ${abo.length === 10 ? 'border-emerald-400 focus:border-emerald-500 focus:ring-emerald-500/20' : 'border-ink-200 focus:border-emerald-500 focus:ring-emerald-500/20'}`} />
              <div className={`text-[10px] mt-1 num ${abo.length === 10 ? 'text-emerald-600' : 'text-ink-400'}`}>{abo.length}/10 หลัก</div>
            </div>
            <div className="col-span-5">
              <label className="text-[10px] uppercase tracking-wider text-ink-500 font-semibold block mb-1.5">วันที่เริ่ม *</label>
              <SixWDatePickerInput value={startDate} onChange={setStartDate} tone="#10B981" />
              <div className="text-[10px] text-ink-400 mt-1">ใช้คำนวณจำนวนวันที่ผ่านมา</div>
            </div>
            <div className="col-span-4">
              <label className="text-[10px] uppercase tracking-wider text-ink-500 font-semibold block mb-1.5">น้ำหนักเริ่ม (kg)</label>
              <input value={startWeight} onChange={e => setStartWeight(e.target.value)} type="number" step="0.1"
                placeholder="78.0"
                className="w-full h-9 px-3 text-sm num border border-ink-200 rounded-lg outline-none focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500/20 bg-white" />
            </div>
            <div className="col-span-4">
              <label className="text-[10px] uppercase tracking-wider text-ink-500 font-semibold block mb-1.5">เป้าหมาย (kg)</label>
              <input value={goalWeight} onChange={e => setGoalWeight(e.target.value)} type="number" step="0.1"
                placeholder="70.0"
                className="w-full h-9 px-3 text-sm num border border-ink-200 rounded-lg outline-none focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500/20 bg-white" />
            </div>
            <div className="col-span-4">
              <label className="text-[10px] uppercase tracking-wider text-ink-500 font-semibold block mb-1.5">ส่วนสูง (cm)</label>
              <input value={height} onChange={e => setHeight(e.target.value)} type="number"
                placeholder="160"
                className="w-full h-9 px-3 text-sm num border border-ink-200 rounded-lg outline-none focus:border-emerald-500 focus:ring-2 focus:ring-emerald-500/20 bg-white" />
            </div>
          </div>

          <label className={`flex items-start gap-3 p-3 rounded-xl border cursor-pointer transition-all ${autoCreateSlide ? 'border-amber-400 bg-gradient-to-br from-amber-50 to-white' : 'border-ink-200 bg-white hover:border-ink-300'}`}>
            <input type="checkbox" checked={autoCreateSlide}
              onChange={e => setAutoCreateSlide(e.target.checked)}
              className="mt-0.5 w-4 h-4 accent-amber-500 flex-shrink-0" />
            <div className="flex-1">
              <div className="flex items-center gap-1.5 mb-0.5">
                <SixWGoogleSlidesIcon className="w-4 h-4" />
                <span className="text-sm font-semibold text-ink-900">สร้าง Google Slides อัตโนมัติ</span>
                <Pill color="#B87C00" tint="#FFECB8" size="xs">แนะนำ</Pill>
              </div>
              <div className="text-[11px] text-ink-500 leading-relaxed">
                ระบบจะ copy template, เติมชื่อลูกค้า + ABO + ข้อมูลเริ่มต้นในสไลด์ และตั้ง share เป็น "ทุกคนที่มีลิงก์" ให้พร้อมใช้
              </div>
            </div>
          </label>
        </div>
      )}
    </Modal>
  );
}

// ============== Banner ==============
function SixWBanner({ customer, onUpdate }) {
  return (
    <div className="flex items-stretch rounded-xl overflow-hidden shadow-card">
      <div className="relative bg-gradient-to-r from-emerald-600 to-emerald-400 text-white px-6 py-3 flex items-center gap-2">
        <Icon name="weight" className="w-5 h-5" />
        <span className="text-lg font-extrabold tracking-wide">ลูกค้าลดน้ำหนัก</span>
        <div className="absolute top-0 bottom-0 -right-4 w-4 bg-emerald-400" style={{ clipPath: 'polygon(0 0, 100% 50%, 0 100%)' }} />
      </div>
      <div className="flex-1 bg-white px-8 py-3 flex flex-wrap items-center gap-x-6 gap-y-2">
        <SixWFieldInline label="ABO" value={customer.abo}
          onChange={v => onUpdate({ abo: v.replace(/\D/g, '').slice(0, 10) })}
          w="w-44" placeholder="10 หลัก" maxLength={10} />
        <SixWFieldInline label="ชื่อ" value={customer.name} onChange={v => onUpdate({ name: v })} w="flex-1 min-w-[200px]" />
      </div>
    </div>
  );
}

function SixWFieldInline({ label, value, onChange, w = 'w-40', placeholder = '', maxLength }) {
  return (
    <div className={`flex items-baseline gap-2 ${w}`}>
      <label className="text-[11px] font-semibold text-ink-500 uppercase tracking-wider flex-shrink-0">{label}</label>
      <input value={value || ''} onChange={e => onChange(e.target.value)} placeholder={placeholder} maxLength={maxLength}
        className="flex-1 text-sm font-medium text-ink-900 bg-transparent outline-none border-b border-dashed border-ink-200 focus:border-brand-500 pb-0.5 transition-colors min-w-0 num" />
    </div>
  );
}

// ============== Progress Hero ==============
function SixWProgressHero({ customer }) {
  const start = parseFloat(customer.em6w?.Before?.uu) || 0;
  const goal = Number(customer.goalWeight) || 0;
  const allWeeks = { ...(customer.em6w || {}), ...(customer.em13w || {}) };
  const weights = Object.entries(allWeeks)
    .filter(([_, v]) => v?.uu)
    .map(([k, v]) => ({ k, w: parseFloat(v.uu) }));
  const last = weights.length ? weights[weights.length - 1].w : start;
  const lost = (start - last).toFixed(1);
  const target = (start - goal).toFixed(1);
  const pct = target > 0 ? Math.max(0, Math.min(1, lost / target)) : 0;
  const currentWeek = Math.max(0, weights.length - 1);
  const totalWeeks = 6;

  // Days-since-start from the Before measurement's date (Thai BE format).
  const startDateStr = customer.em6w?.Before?.date || '';
  const startDateObj = _sixwParseThaiDate(startDateStr);
  const daysSinceStart = startDateObj
    ? Math.max(0, Math.floor((Date.now() - startDateObj.getTime()) / 86400000))
    : null;

  return (
    <Card pad={false} className="bg-gradient-to-br from-emerald-50 via-white to-white border-emerald-100">
      <div className="p-5 grid grid-cols-12 gap-5 items-center">
        <div className="col-span-12 md:col-span-3 flex justify-center">
          <Ring value={pct} size={120} stroke={11} color="#10B981" track="#E7F8F1">
            <div className="text-center">
              <div className="text-2xl font-semibold num text-emerald-700">▼{lost}</div>
              <div className="text-[10px] uppercase tracking-wider text-emerald-700/70 font-semibold">kg lost</div>
            </div>
          </Ring>
        </div>
        <div className="col-span-12 md:col-span-5 grid grid-cols-3 gap-3">
          <SixWHeroStat label="เริ่ม"    value={`${start || '—'}`} unit="kg" />
          <SixWHeroStat label="ปัจจุบัน" value={`${last || '—'}`}  unit="kg" accent="#10B981" big />
          <SixWHeroStat label="เป้า"     value={`${goal || '—'}`}  unit="kg" />
        </div>
        <div className="col-span-12 md:col-span-4">
          <div className="flex items-center justify-between mb-1.5">
            <div className="text-[11px] uppercase tracking-wider text-ink-500 font-semibold">Progress · Week {currentWeek}/{totalWeeks}</div>
            <span className="text-[11px] num font-semibold text-emerald-600">{Math.round(pct * 100)}% สำเร็จ</span>
          </div>
          {daysSinceStart !== null && (
            <div className="text-[11px] text-ink-500 mb-1.5">
              เริ่ม {startDateStr} · ผ่านมา <span className="font-semibold num text-emerald-700">{daysSinceStart}</span> วัน
            </div>
          )}
          <SixWWeightSparkline weights={weights} goal={goal} />
        </div>
      </div>
    </Card>
  );
}

function SixWHeroStat({ label, value, unit, accent, big }) {
  return (
    <div className="text-center">
      <div className="text-[10px] uppercase tracking-wider text-ink-500 font-semibold">{label}</div>
      <div className={`flex items-baseline justify-center gap-0.5 ${big ? 'mt-0.5' : ''}`}>
        <span className={`font-semibold num ${big ? 'text-3xl' : 'text-xl'}`} style={{ color: accent || '#0F1E38' }}>{value}</span>
        <span className="text-[11px] text-ink-400 num">{unit}</span>
      </div>
    </div>
  );
}

function SixWWeightSparkline({ weights, goal }) {
  if (weights.length < 2) {
    return <div className="text-center py-4 text-[11px] text-ink-400">ต้องมีข้อมูล ≥ 2 สัปดาห์</div>;
  }
  const w = 240, h = 70, padL = 10, padR = 10, padT = 8, padB = 8;
  const ys = weights.map(d => d.w);
  const min = Math.min(...ys, goal || ys[0]) - 0.5;
  const max = Math.max(...ys) + 0.5;
  const xScale = (i) => padL + (i / (weights.length - 1)) * (w - padL - padR);
  const yScale = (v) => padT + (1 - (v - min) / (max - min)) * (h - padT - padB);
  const pts = weights.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="grdHero6w" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor="#10B981" stopOpacity="0.4" />
          <stop offset="100%" stopColor="#10B981" stopOpacity="0" />
        </linearGradient>
      </defs>
      {goal > 0 && <line x1={padL} y1={yScale(goal)} x2={w - padR} y2={yScale(goal)} stroke="#94A3B8" strokeWidth="1" strokeDasharray="3 3" />}
      <path d={area} fill="url(#grdHero6w)" />
      <path d={path} stroke="#10B981" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round" />
      {pts.map((p, i) => <circle key={i} cx={p[0]} cy={p[1]} r="3" fill="white" stroke="#10B981" strokeWidth="2" />)}
    </svg>
  );
}

// ============== Customer Info ==============

function SixWCustomerInfoCard({ customer, onUpdate }) {
  const beforeDate = customer.em6w?.Before?.date || '';
  const setStartDate = (v) => {
    const cur = customer.em6w?.Before || {};
    onUpdate({ em6w: { ...(customer.em6w || {}), Before: { ...cur, date: v } } });
  };
  return (
    <Card pad={false} className="bg-gradient-to-br from-brand-50/40 to-white border-brand-100">
      <div className="p-4 grid grid-cols-1 sm:grid-cols-2 gap-4">
        <div>
          <div className="flex items-baseline gap-1.5 mb-1">
            <span className="text-xs">📅</span>
            <label className="text-[10px] uppercase tracking-wider text-ink-500 font-semibold">วันที่เริ่ม</label>
          </div>
          <SixWDatePickerInput value={beforeDate} onChange={setStartDate} tone="#10B981" />
        </div>
        <div>
          <div className="flex items-baseline gap-1.5 mb-1">
            <span className="text-xs">🎯</span>
            <label className="text-[10px] uppercase tracking-wider text-ink-500 font-semibold">เป้าหมายน้ำหนัก</label>
          </div>
          <div className="flex items-baseline gap-1">
            <input
              type="number"
              step="0.1"
              value={customer.goalWeight ?? ''}
              onChange={e => onUpdate({ goalWeight: e.target.value })}
              placeholder="—"
              className="flex-1 h-9 px-3 text-sm num border border-ink-200 rounded-lg outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-500/15 bg-white" />
            <span className="text-[11px] text-ink-400 num">kg</span>
          </div>
        </div>
      </div>
    </Card>
  );
}

// ============== Google Slides — per-customer 6W tracking deck ==============
// One-click: fills the central 6W template with this customer's actual data
// (name, ABO, start date, goal, week-by-week measurements) and opens it in
// Google Slides. Requires the user to have already connected Google in
// Emphasis System → Slide / Plan (or via the inline connect button here).
function _buildSixWTemplate(customer) {
  const beforeDate = customer?.em6w?.Before?.date || '[DD/MM/YYYY]';
  const beforeWeight = customer?.em6w?.Before?.uu || '[xx.x]';
  const goalWeight = customer?.goalWeight ?? '[xx.x]';
  const abo = customer?.abo || '[10 หลัก]';
  const phone = customer?.phone || '[08x-xxx-xxxx]';
  const name = customer?.name || '[ชื่อ-นามสกุล]';
  const sponsor = customer?.sponsor || '[Sponsor]';

  // Pull the 6 weekly readings if we have them.
  const wk = (i) => customer?.em6w?.[`Week ${i}`] || {};
  const weekSlides = [1, 2, 3, 4, 5, 6].map(w => {
    const r = wk(w);
    const weight = r.uu || '[xx.x]';
    const date = r.date || '[DD/MM/YYYY]';
    return {
      title: `📅 สัปดาห์ที่ ${w}`,
      body: [
        `วันที่ check-in: ${date}`,
        `น้ำหนัก: ${weight} kg`,
        `เปลี่ยนแปลง: [▼ x.x kg]`,
        `รอบเอว: [xx] cm`,
        `อาหารที่กิน: [สรุป]`,
        `อารมณ์ / พลังงาน: [ระบุ]`,
        `ปัญหาที่เจอ: [ถ้ามี]`,
        `แผนสัปดาห์ถัดไป: [ระบุ]`,
      ],
    };
  });

  return {
    title: `6W Tracking · ${name}`,
    slides: [
      {
        title: '🥤 6W Tracking',
        body: [
          `ชื่อลูกค้า: ${name}`,
          `ABO Code: ${abo}`,
          `เบอร์ติดต่อ: ${phone}`,
          `วันที่เริ่ม: ${beforeDate}`,
          `Sponsor: ${sponsor}`,
        ],
      },
      {
        title: '🎯 เป้าหมาย & WHY',
        body: [
          `น้ำหนักเริ่มต้น: ${beforeWeight} kg`,
          `น้ำหนักเป้าหมาย: ${goalWeight} kg`,
          `ลดลง: [x.x] kg ภายใน 6 สัปดาห์`,
          `WHY ที่อยากลด: [เหตุผลของลูกค้า]`,
          `เป้าหมายรอบเอว: [xx] cm`,
        ],
      },
      {
        title: '📏 Before · วัดรอบตัว',
        body: [
          `วันที่วัด: ${beforeDate}`,
          `น้ำหนัก: ${beforeWeight} kg`,
          'รอบเอว (Waist): [xx] cm',
          'รอบสะโพก (Hip): [xx] cm',
          'รอบแขน (Arm): [xx] cm',
          'รอบขา (Thigh): [xx] cm',
          'Body Fat %: [xx]%',
          'BMI: [xx.x]',
        ],
      },
      {
        title: '📷 Before · ภาพถ่าย',
        body: [
          'รูปด้านหน้า: [แทรกรูปที่นี่]',
          'รูปด้านข้าง: [แทรกรูปที่นี่]',
          'รูปด้านหลัง: [แทรกรูปที่นี่]',
          'หมายเหตุ: เปลี่ยนชุดเดิมทุกสัปดาห์เพื่อเปรียบเทียบง่ายขึ้น',
        ],
      },
      {
        title: '📦 ชุดผลิตภัณฑ์ที่ใช้',
        body: [
          'BodyKey Shake: [รสชาติ] · [จำนวน]',
          'Meal Bar: [จำนวน]',
          'Nutrilite Double X: [Yes/No]',
          'Phytopowder / Detox: [Yes/No]',
          'อื่นๆ: [ระบุ]',
          'วันส่ง Member Pack: [DD/MM/YYYY]',
        ],
      },
      ...weekSlides,
      {
        title: '🎉 สรุปผล 6 สัปดาห์',
        body: [
          `น้ำหนักก่อน: ${beforeWeight} kg → หลัง: [xx.x] kg`,
          'ลดลงรวม: [x.x] kg ([xx]% ของเป้า)',
          'รอบเอวลดลง: [xx] → [xx] cm',
          'Body Fat ลดลง: [xx]% → [xx]%',
          'รูปเปรียบเทียบ Before / After: [แทรก]',
          'ก้าวต่อไป: [ต่อ EM13W / Maintenance / EM Begin]',
        ],
      },
    ],
  };
}

function SixWGoogleSlidesCard({ customer }) {
  const [busy, setBusy] = useState(false);
  const [result, setResult] = useState(null); // { ok, url?, msg }
  const connected = !!(window.gSlides?.isConnected?.());
  const configured = !!(window.gSlides?.isConfigured?.());

  const handleClick = async () => {
    if (!configured) {
      setResult({ ok: false, msg: 'Google Client ID ยังไม่ได้ตั้งค่า' });
      return;
    }
    setBusy(true); setResult(null);
    try {
      if (!window.gSlides.isConnected()) await window.gSlides.connect();
      const tmpl = _buildSixWTemplate(customer);
      const r = await window.gSlides.createFromTemplate(tmpl);
      setResult({ ok: true, url: r.url, msg: 'สร้าง Google Slides เรียบร้อย' });
      window.open(r.url, '_blank');
    } catch (e) {
      setResult({ ok: false, msg: e.message || 'สร้างไม่สำเร็จ' });
    } finally {
      setBusy(false);
    }
  };

  return (
    <Card pad={false} className="border-emerald-100 bg-gradient-to-br from-emerald-50/40 to-white">
      <div className="p-4 flex items-center gap-3">
        <div className="w-11 h-11 rounded-xl flex items-center justify-center text-white flex-shrink-0"
             style={{ background: '#10B981' }}>
          <svg viewBox="0 0 24 24" fill="currentColor" className="w-5 h-5">
            <path d="M6 2a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6H6zm7 1.5L18.5 9H13V3.5z"/>
          </svg>
        </div>
        <div className="flex-1 min-w-0">
          <div className="text-sm font-semibold text-ink-900">สร้าง Slides Tracking · {customer?.name || '—'}</div>
          <div className="text-[11px] text-ink-500 mt-0.5 leading-relaxed">
            12 หน้า · ข้อมูลพื้นฐาน + Before/After + Week 1-6 + สรุป — ระบบจะ pre-fill ชื่อ · ABO · วันเริ่ม · น้ำหนักให้
          </div>
          {result && (
            <div className={`mt-1.5 text-[11px] ${result.ok ? 'text-emerald-700' : 'text-rose-600'}`}>
              {result.ok ? '✓' : '✗'} {result.msg}
              {result.url && (
                <a href={result.url} target="_blank" rel="noopener noreferrer" className="ml-1 underline font-medium">เปิด ↗</a>
              )}
            </div>
          )}
        </div>
        <Btn variant="brand" size="sm" disabled={busy || !configured} onClick={handleClick}
          icon={<Icon name="plus" className="w-3.5 h-3.5" />}>
          {busy ? 'กำลังสร้าง...' : (connected ? 'สร้าง' : 'เชื่อม + สร้าง')}
        </Btn>
      </div>
    </Card>
  );
}

// ============== Personal Info ==============
function SixWPersonalInfoCard({ customer, onUpdate }) {
  const fields = [
    { id: 'career', label: 'อาชีพ' },
    { id: 'family', label: 'ครอบครัว' },
    { id: 'hobby',  label: 'งานอดิเรก' },
    { id: 'other',  label: 'อาการ/แพ้' },
  ];
  return (
    <Card>
      <div className="space-y-2">
        {fields.map(f => (
          <div key={f.id} className="flex items-baseline gap-3">
            <label className="text-xs text-ink-700 font-medium w-20 flex-shrink-0 text-right">{f.label}</label>
            <input value={customer[f.id] || ''} onChange={e => onUpdate({ [f.id]: e.target.value })}
              className="flex-1 text-sm text-ink-900 bg-transparent outline-none border-b border-dashed border-ink-300 focus:border-brand-500 pb-1" />
          </div>
        ))}
      </div>
    </Card>
  );
}

// ============== Check-up Slide (Google Slides) ==============
function SixWCheckupSlideCard({ customer, onUpdate }) {
  const [editingUrl, setEditingUrl] = useState(false);
  const [draftUrl, setDraftUrl] = useState('');
  const [creating, setCreating] = useState(false);
  const [createStep, setCreateStep] = useState(0);

  const url = customer.checkupSlide || '';
  const hasSlide = url.trim().length > 0;

  const slideId = useMemo(() => {
    const m = url.match(/\/presentation\/d\/([a-zA-Z0-9_-]+)/);
    return m ? m[1] : null;
  }, [url]);

  const editUrl    = slideId ? `https://docs.google.com/presentation/d/${slideId}/edit`    : '#';
  const previewUrl = slideId ? `https://docs.google.com/presentation/d/${slideId}/preview` : '#';
  const embedUrl   = slideId ? `https://docs.google.com/presentation/d/${slideId}/embed?start=false&loop=false` : null;

  const saveUrl = () => { onUpdate({ checkupSlide: draftUrl.trim() }); setEditingUrl(false); };
  const copyLink = async () => { try { await navigator.clipboard.writeText(previewUrl); } catch {} };

  const autoCreate = async () => {
    setCreating(true); setCreateStep(0);
    const steps = ['สร้างสำเนาจาก template','แทนที่ชื่อลูกค้า + ABO ในสไลด์','เติมข้อมูลพื้นฐานทุก week','ตั้งค่า share เป็น ทุกคนที่มีลิงก์'];
    for (let i = 0; i < steps.length; i++) {
      await new Promise(r => setTimeout(r, 500));
      setCreateStep(i + 1);
    }
    const fakeId = '1' + Array.from({length: 43}, () =>
      'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_'
        .charAt(Math.floor(Math.random() * 64))
    ).join('');
    onUpdate({ checkupSlide: `https://docs.google.com/presentation/d/${fakeId}/edit?usp=sharing` });
    setCreating(false); setCreateStep(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-amber-50 to-white">
        <h3 className="text-sm font-extrabold tracking-wide text-amber-700 flex items-center gap-1.5">
          <SixWGoogleSlidesIcon className="w-4 h-4" />
          Check-up Slide · Google Slides
        </h3>
        {hasSlide && (
          <button onClick={() => { setDraftUrl(url); setEditingUrl(true); }}
            className="text-[11px] font-medium text-ink-500 hover:text-ink-900 underline">แก้ไขลิงก์</button>
        )}
      </div>

      {creating ? (
        <div className="p-4">
          <div className="flex items-center gap-3 mb-4">
            <div className="w-10 h-10 rounded-lg bg-amber-100 flex items-center justify-center animate-pulse">
              <SixWGoogleSlidesIcon className="w-5 h-5" />
            </div>
            <div>
              <div className="text-sm font-semibold text-ink-900">กำลังสร้าง Google Slides…</div>
              <div className="text-[11px] text-ink-500">สำหรับ {customer.name}</div>
            </div>
          </div>
          <div className="space-y-2">
            {['สร้างสำเนาจาก template','แทนที่ชื่อลูกค้า + ABO ในสไลด์','เติมข้อมูลพื้นฐานทุก week','ตั้งค่า share เป็น ทุกคนที่มีลิงก์'].map((s, i) => {
              const done = i < createStep;
              const isActive = i === createStep;
              return (
                <div key={i} className="flex items-center gap-2 text-[11px]">
                  <div className={`w-4 h-4 rounded-full flex items-center justify-center flex-shrink-0 ${done ? 'bg-emerald-500' : isActive ? 'bg-amber-400 animate-pulse' : 'bg-ink-200'}`}>
                    {done && <Icon name="check" className="w-2.5 h-2.5 text-white" strokeWidth={3} />}
                  </div>
                  <span className={done ? 'text-ink-700' : isActive ? 'text-ink-900 font-medium' : 'text-ink-400'}>{s}</span>
                </div>
              );
            })}
          </div>
        </div>
      ) : !hasSlide || editingUrl ? (
        <div className="p-4 space-y-3">
          {!hasSlide && (
            <>
              <button onClick={autoCreate}
                className="w-full rounded-xl bg-gradient-to-br from-amber-500 to-amber-400 hover:from-amber-600 hover:to-amber-500 text-white p-4 transition-all text-left group">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 rounded-lg bg-white/20 flex items-center justify-center flex-shrink-0">
                    <Icon name="sparkles" className="w-5 h-5" strokeWidth={2.5} />
                  </div>
                  <div className="flex-1">
                    <div className="text-sm font-bold flex items-center gap-1.5">
                      สร้างอัตโนมัติจาก Template
                      <Icon name="arrowR" className="w-3.5 h-3.5 group-hover:translate-x-0.5 transition-transform" />
                    </div>
                    <div className="text-[11px] opacity-90 mt-0.5">copy template + เติมชื่อ + ABO + ข้อมูลของ {customer.name}</div>
                  </div>
                </div>
              </button>
              <div className="flex items-center gap-2 text-[10px] text-ink-400">
                <div className="flex-1 h-px bg-ink-100" />
                <span>หรือใส่ลิงก์ที่มีอยู่แล้ว</span>
                <div className="flex-1 h-px bg-ink-100" />
              </div>
            </>
          )}
          <div>
            <label className="text-[10px] uppercase tracking-wider text-ink-500 font-semibold block mb-1.5">ลิงก์ Google Slides</label>
            <div className="flex gap-2">
              <input value={draftUrl} onChange={e => setDraftUrl(e.target.value)}
                placeholder="https://docs.google.com/presentation/d/.../edit?usp=sharing"
                autoFocus={editingUrl}
                className="flex-1 h-9 px-3 text-xs border border-ink-200 rounded-lg outline-none focus:border-amber-500 focus:ring-2 focus:ring-amber-500/20 bg-white" />
              <Btn variant="brand" size="sm" icon={<Icon name="check" className="w-3 h-3" />} onClick={saveUrl}>บันทึก</Btn>
              {editingUrl && hasSlide && <Btn variant="ghost" size="sm" onClick={() => setEditingUrl(false)}>ยกเลิก</Btn>}
            </div>
            <div className="text-[10px] text-ink-400 mt-1.5">ตั้ง share เป็น "ทุกคนที่มีลิงก์" เพื่อให้ฝัง preview ในระบบได้</div>
          </div>
        </div>
      ) : (
        <div className="p-4 space-y-3">
          <div className="aspect-video w-full rounded-lg overflow-hidden border border-ink-200 bg-ink-50">
            {embedUrl
              ? <iframe src={embedUrl} className="w-full h-full" frameBorder="0" allowFullScreen title={`Check-up · ${customer.name}`} />
              : <div className="w-full h-full flex items-center justify-center text-xs text-ink-400">ไม่สามารถ embed ได้ — ตรวจสอบสิทธิ์การ share</div>}
          </div>
          <div className="grid grid-cols-2 gap-2">
            <a href={editUrl} target="_blank" rel="noopener noreferrer"
              className="flex items-center justify-center gap-2 py-2.5 rounded-lg bg-amber-500 hover:bg-amber-600 text-white text-xs font-semibold transition-all">
              <svg className="w-3.5 h-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" />
                <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />
              </svg>
              แก้ไขใน Google Slides
            </a>
            <button onClick={copyLink}
              className="flex items-center justify-center gap-2 py-2.5 rounded-lg bg-white border border-ink-200 hover:border-emerald-400 hover:bg-emerald-50/60 text-xs font-semibold text-ink-800 transition-all">
              <Icon name="line" className="w-3.5 h-3.5 text-emerald-600" />
              Copy link ส่ง LINE
            </button>
          </div>
          <div className="flex items-center justify-between text-[10px] pt-1 border-t border-ink-100">
            <code className="text-ink-400 truncate">id: {slideId?.slice(0, 24)}…</code>
            <a href={editUrl} target="_blank" rel="noopener noreferrer" className="text-amber-700 hover:text-amber-900 font-semibold flex-shrink-0">เปิดเต็มจอ ↗</a>
          </div>
        </div>
      )}
    </Card>
  );
}

function SixWGoogleSlidesIcon({ className = 'w-4 h-4' }) {
  return (
    <svg viewBox="0 0 24 24" className={className} fill="none">
      <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6z" fill="#F4B400" />
      <path d="M14 2v6h6" fill="#FFCB45" />
      <rect x="7.5" y="11.5" width="9" height="6" rx="0.5" fill="white" stroke="white" strokeWidth="0.3" />
      <rect x="8.5" y="12.5" width="7" height="1" fill="#F4B400" />
      <rect x="8.5" y="14" width="5" height="0.6" fill="#F4B400" />
      <rect x="8.5" y="15" width="6" height="0.6" fill="#F4B400" />
      <rect x="8.5" y="16" width="4" height="0.6" fill="#F4B400" />
    </svg>
  );
}
