// Settings view — configure appointment types & lead sources live.
// Changes flow into Calendar (Module 5), Dashboard, and LIFF via ConfigContext.

const PRESET_COLORS = [
  '#2F5DE5', '#1B379F', '#8B5CF6', '#EC4899', '#10B981',
  '#06B6D4', '#F59E0B', '#EF4444', '#0EA5E9', '#84CC16',
  '#A855F7', '#F472B6', '#14B8A6', '#FB923C', '#64748B',
];

const PRESET_LABELS = [
  { label: 'CL', full: 'Customer Lead',       desc: 'นัดดูแลลูกค้าหลังการขาย' },
  { label: 'HM', full: 'House Meeting',       desc: 'จัดประชุมที่บ้าน' },
  { label: 'EM', full: 'EM Bridge / Function',desc: 'พาเข้างาน EM Bridge / MFinity' },
  { label: 'TR', full: 'Training',            desc: 'อบรมทีม / สอนงาน' },
  { label: 'CK', full: 'Coaching',            desc: 'โค้ชชิ่ง / Counseling' },
  { label: 'SP', full: 'Skin Care Demo',      desc: 'สาธิตสกินแคร์ / Artistry' },
];

function SettingsView() {
  const { apptTypes, setApptTypes, leadSources, setLeadSources, resetDefaults } = useConfig();
  const [section, setSection] = useState('types');

  return (
    <div className="space-y-5">
      <SectionHead
        eyebrow="Workspace · Configuration"
        title="Settings"
        sub="ตั้งค่ากล่องประเภทนัดหมาย, แหล่งที่มาของผู้มุ่งหวัง — การเปลี่ยนแปลงจะมีผลทันทีในทุกหน้า"
        right={
          <div className="flex items-center gap-2">
            <Btn variant="ghost" size="sm" onClick={() => {
              if (confirm('คืนค่าเริ่มต้นทั้งหมด? การเปลี่ยนแปลงที่ตั้งไว้จะหายไป')) resetDefaults();
            }}>คืนค่าเริ่มต้น</Btn>
            <Pill color="#10B981" tint="#E7F8F1" icon={<span className="w-1.5 h-1.5 rounded-full bg-emerald-500" />}>Auto-saved</Pill>
          </div>
        }
      />

      <div className="grid grid-cols-12 gap-4">
        {/* Section nav */}
        <Card className="col-span-12 lg:col-span-3" pad={false}>
          <div className="p-3">
            <div className="text-[10px] uppercase tracking-wider text-ink-400 px-2 pb-2 font-semibold">Sections</div>
            <ul className="space-y-0.5">
              {[
                { id: 'profile', icon: 'user',     label: 'Profile',           sub: 'ชื่อ, รหัส ABO',         count: '✓' },
                { id: 'login',   icon: 'lock',     label: 'Login & Integrations', sub: 'LINE, Zoom, Google, IG', count: '4' },
                { id: 'types',   icon: 'calendar', label: 'Appointment Types', sub: 'BM / BI / 6W และอื่นๆ', count: apptTypes.length },
                { id: 'sources', icon: 'users',    label: 'Lead Sources',      sub: 'ช่องทางผู้มุ่งหวัง',     count: leadSources.length },
                { id: 'hashtags',icon: 'fire',     label: 'Content Hashtags',  sub: 'สำหรับหน้า Social',     count: '6' },
                { id: 'hours',   icon: 'clock',    label: 'Working Hours',     sub: 'ช่วงเวลาในปฏิทิน',      count: '08–21' },
                { id: 'reminders', icon: 'bell',  label: 'LINE OA Reminders',  sub: 'การแจ้งเตือน LINE',     count: '3' },
              ].map(s => (
                <li key={s.id}>
                  <button onClick={() => setSection(s.id)}
                    className={`w-full flex items-center gap-2.5 px-3 py-2.5 rounded-lg text-left transition-all ${
                      section === s.id ? 'bg-brand-50 text-brand-800' : 'hover:bg-ink-50 text-ink-700'
                    }`}>
                    <Icon name={s.icon} className="w-4 h-4 flex-shrink-0" />
                    <div className="flex-1 min-w-0">
                      <div className="text-xs font-semibold">{s.label}</div>
                      <div className="text-[10px] text-ink-400">{s.sub}</div>
                    </div>
                    <span className="text-[10px] num text-ink-400">{s.count}</span>
                  </button>
                </li>
              ))}
            </ul>
          </div>
          {/* Help card */}
          <div className="m-3 mt-1 p-3 rounded-xl bg-gradient-to-br from-ink-900 to-brand-700 text-white">
            <div className="flex items-center gap-1.5 mb-1.5">
              <Icon name="info" className="w-3.5 h-3.5" />
              <span className="text-[11px] font-semibold">Tip</span>
            </div>
            <p className="text-[11px] leading-relaxed text-white/80">
              เพิ่มประเภทนัดใหม่ได้ไม่จำกัด เช่น <span className="text-gold-300">CL · Customer Lead</span> หรือ <span className="text-gold-300">HM · House Meeting</span> เพื่อแยกประเภทกิจกรรมตามทีมของคุณ
            </p>
          </div>
        </Card>

        {/* Section content */}
        <div className="col-span-12 lg:col-span-9 space-y-4">
          {section === 'profile'  && <ProfileEditor />}
          {section === 'login'    && <LoginIntegrations />}
          {section === 'types'    && <ApptTypesEditor types={apptTypes} setTypes={setApptTypes} />}
          {section === 'sources'  && <LeadSourcesEditor sources={leadSources} setSources={setLeadSources} />}
          {section === 'hashtags' && <HashtagSettings />}
          {section === 'hours'    && <WorkingHoursStub />}
          {section === 'reminders'&& <RemindersStub />}
        </div>
      </div>
    </div>
  );
}

// ===================== Appointment Types editor =====================
function ApptTypesEditor({ types, setTypes }) {
  const [editing, setEditing] = useState(null); // index being edited
  const [showAdd, setShowAdd] = useState(false);

  const updateType = (i, patch) => setTypes(prev => prev.map((t, idx) => idx === i ? { ...t, ...patch } : t));
  const removeType = (i) => setTypes(prev => prev.filter((_, idx) => idx !== i));
  const moveType = (i, dir) => {
    setTypes(prev => {
      const next = [...prev];
      const j = i + dir;
      if (j < 0 || j >= next.length) return prev;
      [next[i], next[j]] = [next[j], next[i]];
      return next;
    });
  };
  const addType = (newType) => {
    setTypes(prev => [...prev, newType]);
    setShowAdd(false);
  };

  return (
    <>
      <Card title={
        <div className="flex items-center gap-2">
          <span className="text-sm font-semibold text-ink-800">Appointment Types</span>
          <span className="text-[11px] text-ink-400">· กล่องที่ลากลงในปฏิทิน</span>
        </div>
      } action={
        <Btn variant="brand" size="sm" icon={<Icon name="plus" className="w-3.5 h-3.5" />} onClick={() => setShowAdd(true)}>
          เพิ่มประเภท
        </Btn>
      }>
        <div className="space-y-2.5">
          {types.map((t, i) => (
            <ApptTypeRow
              key={t.id}
              type={t}
              index={i}
              total={types.length}
              onEdit={() => setEditing(i)}
              onRemove={() => {
                if (confirm(`ลบประเภท "${t.full}"? นัดที่ใช้ประเภทนี้จะยังคงอยู่`)) removeType(i);
              }}
              onMove={(d) => moveType(i, d)}
            />
          ))}
        </div>

        {types.length === 0 && (
          <div className="rounded-xl border border-dashed border-ink-200 p-8 text-center">
            <Icon name="calendar" className="w-8 h-8 text-ink-300 mx-auto" />
            <div className="text-sm text-ink-500 mt-2">ยังไม่มีประเภทนัด</div>
            <Btn variant="brand" size="sm" className="mt-3" icon={<Icon name="plus" className="w-3.5 h-3.5" />} onClick={() => setShowAdd(true)}>เพิ่มประเภทแรก</Btn>
          </div>
        )}
      </Card>

      {/* Live preview row */}
      <Card title="Preview · กล่องประเภทนัด (เหมือนในหน้า Calendar)">
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2.5">
          {types.map(t => (
            <div key={t.id} className="flex items-center gap-3 p-3 rounded-xl border border-ink-100 bg-white">
              <div className="w-9 h-9 rounded-lg flex items-center justify-center text-white font-bold text-xs" style={{ background: t.color }}>{t.label}</div>
              <div className="flex-1 min-w-0">
                <div className="text-sm font-semibold text-ink-900 truncate">{t.full}</div>
                <div className="text-[10px] text-ink-400 truncate">{t.desc}</div>
                <div className="text-[10px] num text-ink-400 mt-0.5">⏱ {t.dur} นาที default</div>
              </div>
            </div>
          ))}
        </div>
      </Card>

      {/* Edit modal */}
      <EditTypeModal
        open={editing !== null}
        onClose={() => setEditing(null)}
        type={editing !== null ? types[editing] : null}
        onSave={(patch) => { updateType(editing, patch); setEditing(null); }}
      />

      {/* Add modal */}
      <AddTypeModal
        open={showAdd}
        existing={types}
        onClose={() => setShowAdd(false)}
        onSave={addType}
      />
    </>
  );
}

function ApptTypeRow({ type, index, total, onEdit, onRemove, onMove }) {
  return (
    <div className="flex items-center gap-3 p-3 rounded-xl border border-ink-100 bg-white hover:shadow-card transition-all">
      {/* Reorder */}
      <div className="flex flex-col gap-0.5">
        <button onClick={() => onMove(-1)} disabled={index === 0} className="text-ink-300 hover:text-ink-700 disabled:opacity-30 disabled:cursor-not-allowed">
          <svg className="w-3 h-3" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 7l3-3 3 3" strokeLinecap="round" strokeLinejoin="round" /></svg>
        </button>
        <button onClick={() => onMove(1)} disabled={index === total-1} className="text-ink-300 hover:text-ink-700 disabled:opacity-30 disabled:cursor-not-allowed">
          <svg className="w-3 h-3" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 5l3 3 3-3" strokeLinecap="round" strokeLinejoin="round" /></svg>
        </button>
      </div>

      {/* Color swatch + label */}
      <div className="w-12 h-12 rounded-lg flex items-center justify-center text-white font-bold flex-shrink-0" style={{ background: type.color }}>
        {type.label}
      </div>

      {/* Info */}
      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-2">
          <span className="text-sm font-semibold text-ink-900 truncate">{type.full}</span>
          <code className="text-[10px] font-mono text-ink-500 bg-ink-50 px-1.5 py-0.5 rounded">{type.id}</code>
        </div>
        <div className="text-[11px] text-ink-500 truncate">{type.desc}</div>
      </div>

      {/* Duration */}
      <div className="text-right flex-shrink-0">
        <div className="text-[10px] uppercase tracking-wider text-ink-400">Default</div>
        <div className="text-sm font-semibold num text-ink-900">{type.dur} min</div>
      </div>

      {/* Actions */}
      <div className="flex items-center gap-1 flex-shrink-0">
        <button onClick={onEdit} className="w-8 h-8 rounded-md border border-ink-200 flex items-center justify-center text-ink-600 hover:bg-ink-50">
          <svg className="w-3.5 h-3.5" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.75"><path d="M11 2l3 3-9 9H2v-3l9-9z" strokeLinejoin="round" /></svg>
        </button>
        <button onClick={onRemove} className="w-8 h-8 rounded-md border border-ink-200 flex items-center justify-center text-rose-500 hover:bg-rose-50 hover:border-rose-200">
          <svg className="w-3.5 h-3.5" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.75"><path d="M3 4h10M6 4V2h4v2M5 4l1 10h4l1-10" strokeLinecap="round" strokeLinejoin="round" /></svg>
        </button>
      </div>
    </div>
  );
}

// ===================== Edit Type Modal =====================
function EditTypeModal({ open, onClose, type, onSave }) {
  const [label, setLabel] = useState('');
  const [full, setFull] = useState('');
  const [desc, setDesc] = useState('');
  const [dur, setDur] = useState(60);
  const [color, setColor] = useState('#2F5DE5');

  useEffect(() => {
    if (type) {
      setLabel(type.label); setFull(type.full); setDesc(type.desc); setDur(type.dur); setColor(type.color);
    }
  }, [type]);

  if (!type) return null;

  // Tint = color at ~12% opacity (computed hex)
  const tint = colorTint(color);

  return (
    <Modal open={open} onClose={onClose} title="แก้ไขประเภทนัด" size="lg"
      footer={
        <div className="flex items-center justify-between">
          <span className="text-[11px] text-ink-400 num">ID: <code className="font-mono">{type.id}</code></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={() => onSave({ label, full, desc, dur, color, tint })}>บันทึก</Btn>
          </div>
        </div>
      }>
      <div className="grid grid-cols-12 gap-4">
        {/* Live preview */}
        <div className="col-span-12">
          <div className="text-[10px] uppercase tracking-wider text-ink-400 mb-2 font-semibold">Preview</div>
          <div className="flex items-center gap-3 p-3 rounded-xl border border-ink-200 bg-ink-50">
            <div className="w-12 h-12 rounded-lg flex items-center justify-center text-white font-bold" style={{ background: color }}>{label}</div>
            <div className="flex-1">
              <div className="text-sm font-semibold text-ink-900">{full || 'Untitled'}</div>
              <div className="text-[11px] text-ink-500">{desc || 'ใส่คำอธิบายที่นี่'}</div>
              <div className="text-[10px] num text-ink-400 mt-0.5">⏱ {dur} นาที default</div>
            </div>
            {/* Sample card on tinted bg */}
            <div className="w-32 rounded-md p-2 border" style={{ background: tint, borderColor: color + '40', borderLeft: `3px solid ${color}` }}>
              <span className="text-[10px] font-bold px-1.5 rounded-sm text-white" style={{ background: color }}>{label}</span>
              <div className="text-[11px] font-semibold text-ink-900 mt-1">คุณวริศรา ม.</div>
            </div>
          </div>
        </div>

        {/* Fields */}
        <div className="col-span-12 sm:col-span-3">
          <FieldLabel>Label (2 ตัวอักษร)</FieldLabel>
          <input value={label} onChange={e => setLabel(e.target.value.slice(0,3).toUpperCase())} className="settings-input num font-bold text-center text-base" maxLength={3} />
        </div>
        <div className="col-span-12 sm:col-span-9">
          <FieldLabel>ชื่อเต็ม (Full name)</FieldLabel>
          <input value={full} onChange={e => setFull(e.target.value)} className="settings-input" placeholder="เช่น Business Model" />
        </div>

        <div className="col-span-12">
          <FieldLabel>คำอธิบาย</FieldLabel>
          <input value={desc} onChange={e => setDesc(e.target.value)} className="settings-input" placeholder="คำอธิบายสั้นๆ" />
        </div>

        <div className="col-span-12">
          <FieldLabel>ระยะเวลาเริ่มต้น (Default duration)</FieldLabel>
          <div className="flex items-center gap-3">
            <input type="range" min={15} max={180} step={15} value={dur} onChange={e => setDur(parseInt(e.target.value))} className="flex-1 accent-brand-500" />
            <div className="flex items-center gap-1 w-32 justify-end">
              <input type="number" min={5} max={480} step={5} value={dur} onChange={e => setDur(parseInt(e.target.value) || 0)} className="settings-input w-16 text-right num" />
              <span className="text-xs text-ink-500">นาที</span>
            </div>
          </div>
          <div className="flex gap-1 mt-2">
            {[15, 30, 45, 60, 90, 120].map(d => (
              <button key={d} onClick={() => setDur(d)} className={`text-[11px] font-medium px-2 py-1 rounded-md border transition-all ${dur === d ? 'bg-ink-900 text-white border-transparent' : 'bg-white border-ink-200 text-ink-600 hover:border-ink-300'}`}>{d}m</button>
            ))}
          </div>
        </div>

        <div className="col-span-12">
          <FieldLabel>สีของกล่อง</FieldLabel>
          <ColorPicker value={color} onChange={setColor} />
        </div>
      </div>
      <style>{`
        .settings-input {
          width: 100%; padding: 8px 12px; font-size: 13px;
          border: 1px solid #C9D2E3; border-radius: 8px; background: white;
          outline: none; transition: all .15s; color: #0F1E38;
        }
        .settings-input:focus { border-color: #2F5DE5; box-shadow: 0 0 0 3px rgba(47,93,229,0.15); }
      `}</style>
    </Modal>
  );
}

// ===================== Add Type Modal =====================
function AddTypeModal({ open, existing, onClose, onSave }) {
  const [label, setLabel] = useState('CL');
  const [full, setFull] = useState('');
  const [desc, setDesc] = useState('');
  const [dur, setDur] = useState(60);
  const [color, setColor] = useState(PRESET_COLORS[5]);

  useEffect(() => {
    if (open) {
      // Suggest the next preset that's not used
      const used = new Set(existing.map(t => t.label.toUpperCase()));
      const suggestion = PRESET_LABELS.find(p => !used.has(p.label)) || { label: 'NEW', full: 'New Topic', desc: '' };
      setLabel(suggestion.label); setFull(suggestion.full); setDesc(suggestion.desc);
      setDur(60); setColor(PRESET_COLORS[(existing.length * 3) % PRESET_COLORS.length]);
    }
  }, [open]);

  const handleSave = () => {
    if (!label.trim() || !full.trim()) return;
    const id = label.toUpperCase().slice(0, 6);
    // Ensure unique id
    const baseId = id;
    let finalId = baseId;
    let n = 2;
    while (existing.some(t => t.id === finalId)) { finalId = `${baseId}${n}`; n++; }
    onSave({ id: finalId, label: label.toUpperCase(), full, desc, dur, color, tint: colorTint(color) });
  };

  const tint = colorTint(color);

  return (
    <Modal open={open} onClose={onClose} title={
      <div className="flex items-center gap-2">
        <div className="w-7 h-7 rounded-md bg-brand-500 text-white flex items-center justify-center"><Icon name="plus" className="w-4 h-4" /></div>
        <span className="text-sm font-semibold text-ink-900">เพิ่มประเภทนัดใหม่</span>
      </div>
    } size="lg" footer={
      <div className="flex items-center justify-between">
        <span className="text-[11px] text-ink-400">การเปลี่ยนแปลงจะมีผลทันทีในทุกหน้าที่ใช้ประเภทนัด</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={handleSave}>สร้าง</Btn>
        </div>
      </div>
    }>
      {/* Quick presets */}
      <div className="mb-4">
        <FieldLabel>เลือกจาก preset</FieldLabel>
        <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
          {PRESET_LABELS.map((p, i) => {
            const used = existing.some(t => t.label === p.label);
            return (
              <button key={p.label} disabled={used}
                onClick={() => { setLabel(p.label); setFull(p.full); setDesc(p.desc); setColor(PRESET_COLORS[(i + 4) % PRESET_COLORS.length]); }}
                className={`flex items-center gap-2 p-2 rounded-lg border text-left transition-all ${used ? 'opacity-40 cursor-not-allowed bg-ink-50 border-ink-100' : 'bg-white border-ink-200 hover:border-brand-300 hover:bg-brand-50/40'}`}>
                <div className="w-7 h-7 rounded text-white font-bold text-[10px] flex items-center justify-center" style={{ background: PRESET_COLORS[(i + 4) % PRESET_COLORS.length] }}>{p.label}</div>
                <div className="min-w-0">
                  <div className="text-xs font-semibold text-ink-900 truncate">{p.full}</div>
                  <div className="text-[10px] text-ink-400 truncate">{used ? 'มีอยู่แล้ว' : p.desc}</div>
                </div>
              </button>
            );
          })}
        </div>
      </div>

      <div className="border-t border-ink-100 pt-4 grid grid-cols-12 gap-4">
        <div className="col-span-12">
          <div className="text-[10px] uppercase tracking-wider text-ink-400 mb-2 font-semibold">Live preview</div>
          <div className="flex items-center gap-3 p-3 rounded-xl border border-ink-200 bg-ink-50">
            <div className="w-12 h-12 rounded-lg flex items-center justify-center text-white font-bold" style={{ background: color }}>{label}</div>
            <div className="flex-1">
              <div className="text-sm font-semibold text-ink-900">{full || 'Untitled'}</div>
              <div className="text-[11px] text-ink-500">{desc || 'คำอธิบาย'}</div>
              <div className="text-[10px] num text-ink-400 mt-0.5">⏱ {dur} นาที default</div>
            </div>
            <div className="w-32 rounded-md p-2 border" style={{ background: tint, borderColor: color + '40', borderLeft: `3px solid ${color}` }}>
              <span className="text-[10px] font-bold px-1.5 rounded-sm text-white" style={{ background: color }}>{label}</span>
              <div className="text-[11px] font-semibold text-ink-900 mt-1">ผู้มุ่งหวัง</div>
            </div>
          </div>
        </div>

        <div className="col-span-12 sm:col-span-3">
          <FieldLabel>Label</FieldLabel>
          <input value={label} onChange={e => setLabel(e.target.value.slice(0,3).toUpperCase())} className="settings-input num font-bold text-center text-base" maxLength={3} />
        </div>
        <div className="col-span-12 sm:col-span-9">
          <FieldLabel>ชื่อเต็ม</FieldLabel>
          <input value={full} onChange={e => setFull(e.target.value)} className="settings-input" placeholder="เช่น Customer Lead" />
        </div>

        <div className="col-span-12">
          <FieldLabel>คำอธิบาย</FieldLabel>
          <input value={desc} onChange={e => setDesc(e.target.value)} className="settings-input" placeholder="คำอธิบายสั้นๆ" />
        </div>

        <div className="col-span-12">
          <FieldLabel>ระยะเวลาเริ่มต้น</FieldLabel>
          <div className="flex items-center gap-3">
            <input type="range" min={15} max={180} step={15} value={dur} onChange={e => setDur(parseInt(e.target.value))} className="flex-1 accent-brand-500" />
            <div className="flex items-center gap-1 w-32 justify-end">
              <input type="number" min={5} max={480} step={5} value={dur} onChange={e => setDur(parseInt(e.target.value) || 0)} className="settings-input w-16 text-right num" />
              <span className="text-xs text-ink-500">นาที</span>
            </div>
          </div>
          <div className="flex gap-1 mt-2">
            {[15, 30, 45, 60, 90, 120].map(d => (
              <button key={d} onClick={() => setDur(d)} className={`text-[11px] font-medium px-2 py-1 rounded-md border transition-all ${dur === d ? 'bg-ink-900 text-white border-transparent' : 'bg-white border-ink-200 text-ink-600 hover:border-ink-300'}`}>{d}m</button>
            ))}
          </div>
        </div>

        <div className="col-span-12">
          <FieldLabel>สี</FieldLabel>
          <ColorPicker value={color} onChange={setColor} />
        </div>
      </div>
      <style>{`
        .settings-input {
          width: 100%; padding: 8px 12px; font-size: 13px;
          border: 1px solid #C9D2E3; border-radius: 8px; background: white;
          outline: none; transition: all .15s; color: #0F1E38;
        }
        .settings-input:focus { border-color: #2F5DE5; box-shadow: 0 0 0 3px rgba(47,93,229,0.15); }
      `}</style>
    </Modal>
  );
}

function ColorPicker({ value, onChange }) {
  return (
    <div className="flex flex-wrap gap-2">
      {PRESET_COLORS.map(c => (
        <button key={c} onClick={() => onChange(c)}
          className={`w-8 h-8 rounded-lg transition-all relative ${value === c ? 'ring-2 ring-offset-2 ring-ink-900 scale-110' : 'hover:scale-105'}`}
          style={{ background: c }}>
          {value === c && <Icon name="check" className="w-4 h-4 text-white absolute inset-0 m-auto" strokeWidth={3} />}
        </button>
      ))}
      <label className="w-8 h-8 rounded-lg border-2 border-dashed border-ink-300 flex items-center justify-center cursor-pointer hover:border-ink-500 relative overflow-hidden">
        <input type="color" value={value} onChange={e => onChange(e.target.value)} className="absolute inset-0 opacity-0 cursor-pointer w-full h-full" />
        <svg className="w-3.5 h-3.5 text-ink-500" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.75"><path d="M3 12l9-9 1 1-9 9-1-1z" /><path d="M2 14h2" /></svg>
      </label>
    </div>
  );
}

// ===================== Lead Sources editor =====================
function LeadSourcesEditor({ sources, setSources }) {
  const [draft, setDraft] = useState(null); // { id, label, color }
  const [adding, setAdding] = useState(false);
  const [newLabel, setNewLabel] = useState('');
  const [newColor, setNewColor] = useState(PRESET_COLORS[0]);

  return (
    <Card title={
      <div className="flex items-center gap-2">
        <span className="text-sm font-semibold text-ink-800">Lead Sources</span>
        <span className="text-[11px] text-ink-400">· แหล่งที่มาของผู้มุ่งหวัง</span>
      </div>
    } action={
      adding ? null : <Btn variant="brand" size="sm" icon={<Icon name="plus" className="w-3.5 h-3.5" />} onClick={() => setAdding(true)}>เพิ่มแหล่ง</Btn>
    }>
      <div className="space-y-2">
        {sources.map((s, i) => (
          <div key={s.id} className="flex items-center gap-3 p-2.5 rounded-lg border border-ink-100 bg-white">
            <input type="color" value={s.color} onChange={e => setSources(prev => prev.map((x, idx) => idx === i ? { ...x, color: e.target.value } : x))}
                   className="w-7 h-7 rounded-md cursor-pointer flex-shrink-0 bg-transparent border-none p-0" />
            <input value={s.label}
                   onChange={e => setSources(prev => prev.map((x, idx) => idx === i ? { ...x, label: e.target.value } : x))}
                   className="flex-1 text-sm font-medium text-ink-900 bg-transparent outline-none border-b border-transparent focus:border-brand-500 px-1" />
            <code className="text-[10px] font-mono text-ink-400 bg-ink-50 px-1.5 py-0.5 rounded">{s.id}</code>
            <button onClick={() => { if (confirm(`ลบแหล่ง "${s.label}"?`)) setSources(prev => prev.filter((_, idx) => idx !== i)); }}
                    className="w-7 h-7 rounded-md border border-ink-200 flex items-center justify-center text-rose-500 hover:bg-rose-50 hover:border-rose-200">
              <svg className="w-3 h-3" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.75"><path d="M3 4h10M5 4l1 10h4l1-10" strokeLinecap="round" /></svg>
            </button>
          </div>
        ))}
        {adding && (
          <div className="flex items-center gap-3 p-2.5 rounded-lg border border-brand-300 bg-brand-50/40">
            <input type="color" value={newColor} onChange={e => setNewColor(e.target.value)} className="w-7 h-7 rounded-md cursor-pointer flex-shrink-0 bg-transparent border-none p-0" />
            <input value={newLabel} onChange={e => setNewLabel(e.target.value)} autoFocus placeholder="ชื่อแหล่ง เช่น TikTok Shop"
                   className="flex-1 text-sm font-medium text-ink-900 bg-transparent outline-none border-b border-brand-300 focus:border-brand-500 px-1" />
            <Btn variant="brand" size="sm" onClick={() => {
              if (!newLabel.trim()) return;
              const id = newLabel.toLowerCase().replace(/\s+/g, '_').slice(0, 12) + '_' + Math.random().toString(36).slice(2, 5);
              setSources(prev => [...prev, { id, label: newLabel, color: newColor }]);
              setAdding(false); setNewLabel('');
            }}>เพิ่ม</Btn>
            <Btn variant="ghost" size="sm" onClick={() => { setAdding(false); setNewLabel(''); }}>ยกเลิก</Btn>
          </div>
        )}
      </div>
    </Card>
  );
}

// ===================== Stubs for future =====================
function WorkingHoursStub() {
  return (
    <Card title="Working Hours">
      <div className="grid grid-cols-2 gap-3 mb-4">
        <div>
          <FieldLabel>เวลาเริ่ม</FieldLabel>
          <input type="time" defaultValue="08:00" className="settings-input num" />
        </div>
        <div>
          <FieldLabel>เวลาสิ้นสุด</FieldLabel>
          <input type="time" defaultValue="21:00" className="settings-input num" />
        </div>
      </div>
      <FieldLabel>วันทำงาน</FieldLabel>
      <div className="grid grid-cols-7 gap-1">
        {['จ.', 'อ.', 'พ.', 'พฤ.', 'ศ.', 'ส.', 'อา.'].map((d, i) => (
          <label key={d} className={`flex items-center justify-center py-2 rounded-md text-xs font-medium border cursor-pointer ${i < 5 ? 'bg-brand-50 border-brand-200 text-brand-700' : 'bg-white border-ink-200 text-ink-500'}`}>
            <input type="checkbox" defaultChecked={i < 6} className="sr-only" />
            {d}
          </label>
        ))}
      </div>
      <div className="mt-4 text-[11px] text-ink-400">เวลาเหล่านี้จะเป็นช่วงที่แสดงในปฏิทินรายสัปดาห์</div>
      <style>{`.settings-input{width:100%;padding:8px 12px;font-size:13px;border:1px solid #C9D2E3;border-radius:8px;background:white;outline:none;color:#0F1E38}.settings-input:focus{border-color:#2F5DE5;box-shadow:0 0 0 3px rgba(47,93,229,.15)}`}</style>
    </Card>
  );
}

function RemindersStub() {
  const reminders = [
    { id: 1, label: 'นัด T-1 day',       desc: 'แจ้งเตือนผู้นัด 1 วันก่อนนัด',            on: true,  channel: 'LINE Push' },
    { id: 2, label: 'นัดถึงเวลา',         desc: 'แจ้งเตือนทั้งผู้นัดและ Leader',          on: true,  channel: 'LINE Push' },
    { id: 3, label: 'SOP รอบตัด T-3',    desc: 'เตือนลูกค้า SOP 3 วันก่อนรอบตัดบัตร',     on: true,  channel: 'LINE Push' },
    { id: 4, label: 'Weekly digest',     desc: 'สรุปประจำสัปดาห์ — จันทร์ 9:00 น.',      on: true,  channel: 'Flex Message → Leader' },
    { id: 5, label: 'BT achievement',    desc: 'broadcast เมื่อมีคนผ่าน BT',             on: false, channel: 'Flex Card · Upline + Downline' },
  ];
  return (
    <Card title="Reminders · LINE Messaging">
      <div className="space-y-2">
        {reminders.map(r => (
          <div key={r.id} className="flex items-center gap-3 p-3 rounded-xl border border-ink-100 bg-white">
            <div className="w-9 h-9 rounded-lg bg-emerald-50 text-emerald-600 flex items-center justify-center flex-shrink-0">
              <Icon name="bell" className="w-4 h-4" />
            </div>
            <div className="flex-1 min-w-0">
              <div className="text-sm font-semibold text-ink-900">{r.label}</div>
              <div className="text-[11px] text-ink-500">{r.desc}</div>
              <div className="text-[10px] text-ink-400 mt-0.5">via {r.channel}</div>
            </div>
            <Toggle defaultOn={r.on} />
          </div>
        ))}
      </div>
    </Card>
  );
}

function Toggle({ defaultOn }) {
  const [on, setOn] = useState(defaultOn);
  return (
    <button onClick={() => setOn(!on)}
      className={`relative w-10 h-6 rounded-full transition-colors flex-shrink-0 ${on ? 'bg-emerald-500' : 'bg-ink-200'}`}>
      <div className={`absolute top-0.5 w-5 h-5 rounded-full bg-white shadow-md transition-all ${on ? 'left-[18px]' : 'left-0.5'}`} />
    </button>
  );
}

function FieldLabel({ children }) {
  return <div className="text-[11px] font-medium text-ink-500 mb-1.5 uppercase tracking-wide">{children}</div>;
}

// Compute a light tint from a hex color (mix with white ~88%)
function colorTint(hex) {
  const h = hex.replace('#', '');
  const r = parseInt(h.slice(0,2), 16);
  const g = parseInt(h.slice(2,4), 16);
  const b = parseInt(h.slice(4,6), 16);
  const mix = (c) => Math.round(c + (255 - c) * 0.88);
  const toHex = (n) => n.toString(16).padStart(2, '0');
  return '#' + toHex(mix(r)) + toHex(mix(g)) + toHex(mix(b));
}

// ===================== Profile editor =====================
function ProfileEditor() {
  const [name, setName] = useState('พิมพ์ชนก ศ.');
  const [abo, setAbo] = useState('TH-9201853');
  const [phone, setPhone] = useState('081-234-5678');
  const [country, setCountry] = useState('th');
  return (
    <Card title="ข้อมูลพื้นฐาน">
      <div className="space-y-3">
        <SetField label="ชื่อ-นามสกุล"><input value={name} onChange={e => setName(e.target.value)} className="w-full h-10 px-3 text-sm border border-ink-200 rounded-lg outline-none focus:border-brand-500" /></SetField>
        <SetField label="ABO Code"><input value={abo} onChange={e => setAbo(e.target.value)} className="w-full h-10 px-3 text-sm border border-ink-200 rounded-lg outline-none focus:border-brand-500 num" /></SetField>
        <SetField label="เบอร์ติดต่อ"><input value={phone} onChange={e => setPhone(e.target.value)} className="w-full h-10 px-3 text-sm border border-ink-200 rounded-lg outline-none focus:border-brand-500 num" /></SetField>
        <SetField label="ประเทศหลัก">
          <div className="flex items-center gap-2">
            {window.COUNTRIES.map(c => (
              <button key={c.id} onClick={() => setCountry(c.id)}
                className={`flex items-center gap-2 px-3 h-10 rounded-lg border text-sm ${country === c.id ? 'border-brand-500 bg-brand-50 text-brand-700 font-semibold' : 'border-ink-200 text-ink-600 hover:bg-ink-50'}`}>
                <span className="text-base">{c.flag}</span>{c.label}
              </button>
            ))}
          </div>
        </SetField>
        <div className="pt-3 border-t border-ink-100">
          <Btn variant="brand" size="sm" icon={<Icon name="check" className="w-3.5 h-3.5" />}>บันทึก</Btn>
        </div>
      </div>
    </Card>
  );
}

// ===================== Login & Integrations =====================
function LoginIntegrations() {
  const [items, setItems] = useState([
    { id: 'line',   label: 'LINE',            desc: 'เข้าระบบและรับการแจ้งเตือนผ่าน LINE',          icon: 'line',     color: '#06C755', connected: true,  account: '@pim_emphasis · U_demo_001' },
    { id: 'zoom',   label: 'Zoom',            desc: 'สร้างห้องประชุมจากปฏิทินอัตโนมัติ',              icon: 'zoom',     color: '#2D8CFF', connected: false, account: '' },
    { id: 'gcal',   label: 'Google Calendar', desc: 'Sync นัดหมายไปยัง Google Calendar',          icon: 'calendar', color: '#4285F4', connected: true,  account: 'pim.b@gmail.com' },
    { id: 'ig',     label: 'Instagram',       desc: 'ดึงโปรไฟล์ผู้มุ่งหวังจาก IG handle',              icon: 'sparkles', color: '#E1306C', connected: false, account: '' },
  ]);
  const [igHandle, setIgHandle] = useState('@pim.business');

  const toggle = (id) => setItems(items.map(it => it.id === id ? { ...it, connected: !it.connected } : it));

  return (
    <div className="space-y-4">
      <Card title="การเชื่อมต่อบัญชี (Login & Integrations)">
        <div className="space-y-2">
          {items.map(it => (
            <div key={it.id} className="flex items-center gap-3 p-3 border border-ink-100 rounded-xl hover:bg-ink-50/30">
              <div className="w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0" style={{ background: it.color + '20', color: it.color }}>
                <Icon name={it.icon} className="w-5 h-5" />
              </div>
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2">
                  <span className="text-sm font-semibold text-ink-900">{it.label}</span>
                  {it.connected
                    ? <Pill color="#10B981" tint="#E7F8F1" size="xs" icon={<span className="w-1 h-1 rounded-full bg-emerald-500" />}>เชื่อมแล้ว</Pill>
                    : <Pill color="#94A3B8" tint="#F1F5F9" size="xs">ยังไม่เชื่อม</Pill>}
                </div>
                <div className="text-[11px] text-ink-500 mt-0.5">{it.desc}</div>
                {it.connected && it.account && <div className="text-[10px] text-ink-400 num mt-0.5">{it.account}</div>}
              </div>
              <button onClick={() => toggle(it.id)}
                className={`text-xs font-medium px-3 h-8 rounded-lg transition-all ${it.connected ? 'bg-ink-100 text-ink-600 hover:bg-rose-50 hover:text-rose-600' : 'text-white'}`}
                style={!it.connected ? { background: it.color } : {}}>
                {it.connected ? 'ตัดการเชื่อมต่อ' : 'เชื่อมต่อ'}
              </button>
            </div>
          ))}
        </div>
      </Card>

      <Card title="Instagram Handle (สำหรับ Prospect Sourcing)">
        <SetField label="Instagram Username">
          <div className="flex items-center gap-2">
            <input value={igHandle} onChange={e => setIgHandle(e.target.value)} className="flex-1 h-10 px-3 text-sm border border-ink-200 rounded-lg outline-none focus:border-pink-400" placeholder="@username" />
            <Btn variant="brand" size="sm" icon={<Icon name="refresh" className="w-3.5 h-3.5" />}>ทดสอบดึงรูป</Btn>
          </div>
          <div className="text-[11px] text-ink-500 mt-1.5">เมื่อสร้างนัดและเลือกแหล่ง = Instagram, ระบบจะใช้ API หลังบ้านดึงรูปโปรไฟล์มาแสดง</div>
        </SetField>
      </Card>
    </div>
  );
}

// ===================== Content Hashtags =====================
function HashtagSettings() {
  const [tags, setTags] = useState([
    { id: 1, label: '#พัฒนาตัวเอง',  enabled: true,  category: 'self' },
    { id: 2, label: '#mindset',       enabled: true,  category: 'self' },
    { id: 3, label: '#ธุรกิจ',          enabled: true,  category: 'biz' },
    { id: 4, label: '#รายได้เสริม',     enabled: true,  category: 'biz' },
    { id: 5, label: '#ลดน้ำหนัก',      enabled: true,  category: 'health' },
    { id: 6, label: '#bodykey',       enabled: true,  category: 'health' },
    { id: 7, label: '#lifestyle',     enabled: false, category: 'life' },
    { id: 8, label: '#wellness',      enabled: false, category: 'life' },
  ]);
  const [newTag, setNewTag] = useState('');

  const toggle = (id) => setTags(tags.map(t => t.id === id ? { ...t, enabled: !t.enabled } : t));
  const remove = (id) => setTags(tags.filter(t => t.id !== id));
  const add = () => {
    if (!newTag.trim()) return;
    const label = newTag.startsWith('#') ? newTag : '#' + newTag;
    setTags([...tags, { id: Date.now(), label, enabled: true, category: 'custom' }]);
    setNewTag('');
  };

  const catColors = { self: '#7C3AED', biz: '#2F5DE5', health: '#10B981', life: '#F59E0B', custom: '#64748B' };
  const catLabel = { self: 'พัฒนาตัวเอง', biz: 'ธุรกิจ', health: 'สุขภาพ', life: 'Lifestyle', custom: 'อื่นๆ' };

  return (
    <Card title="Hashtag สำหรับการ Track Content"
          action={<span className="text-[11px] text-ink-400">ใช้แสดงเนื้อหา trending ในหน้า Social Dashboard</span>}>
      <div className="mb-4 flex items-center gap-2">
        <input value={newTag} onChange={e => setNewTag(e.target.value)} onKeyDown={e => e.key === 'Enter' && add()}
               className="flex-1 h-10 px-3 text-sm border border-ink-200 rounded-lg outline-none focus:border-brand-500"
               placeholder="พิมพ์ hashtag ใหม่ เช่น #moneymindset" />
        <Btn variant="brand" size="sm" icon={<Icon name="plus" />} onClick={add}>เพิ่ม</Btn>
      </div>

      <div className="space-y-3">
        {['self', 'biz', 'health', 'life', 'custom'].map(cat => {
          const list = tags.filter(t => t.category === cat);
          if (list.length === 0) return null;
          return (
            <div key={cat}>
              <div className="flex items-center gap-2 mb-2">
                <Pill color={catColors[cat]} tint={catColors[cat] + '20'} size="xs">{catLabel[cat]}</Pill>
                <span className="text-[10px] text-ink-400 num">{list.length} tags</span>
              </div>
              <div className="flex flex-wrap gap-1.5">
                {list.map(t => (
                  <div key={t.id} className={`group inline-flex items-center gap-1.5 pl-3 pr-1.5 py-1.5 rounded-full text-xs border ${t.enabled ? 'bg-brand-50 border-brand-200 text-brand-800' : 'bg-ink-50 border-ink-200 text-ink-400'}`}>
                    <button onClick={() => toggle(t.id)} className="font-medium">{t.label}</button>
                    <button onClick={() => remove(t.id)} className="w-5 h-5 rounded-full hover:bg-rose-100 hover:text-rose-600 text-ink-400 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
                      <Icon name="x" className="w-3 h-3" strokeWidth={2.5} />
                    </button>
                  </div>
                ))}
              </div>
            </div>
          );
        })}
      </div>
    </Card>
  );
}

function SetField({ label, children }) {
  return (
    <div>
      <label className="text-[11px] uppercase tracking-wider font-semibold text-ink-500 mb-1.5 block">{label}</label>
      {children}
    </div>
  );
}

window.SettingsView = SettingsView;
