// One Call Order — dedicated application form keyed from the Call Flow worksheet
// Sections mirror the uploaded Excel: Company info · Call-flow features · IVR builder (office / non-office) · Review

// Build a 30-minute time option list 00:00 → 23:30
const OC_TIME_OPTIONS = Array.from({ length: 48 }, (_, i) => {
  const h = Math.floor(i / 2); const m = i % 2 ? '30' : '00';
  return String(h).padStart(2, '0') + ':' + m;
});

// Call-distribution methods (within a department)
const OC_DIST_OPTIONS = [
  { v: 'linear',      l: 'Linear',      th: 'เรียงตามลำดับ' },
  { v: 'ring_all',    l: 'Ring all',    th: 'ดังพร้อมกันทุกเครื่อง' },
  { v: 'circular',    l: 'Circular',    th: 'วนรอบต่อจากครั้งก่อน' },
  { v: 'round_robin', l: 'Round robin', th: 'กระจายเท่ากันทุกเครื่อง' },
  { v: 'longest_idle',l: 'Longest idle',th: 'เครื่องที่ว่างนานสุด' },
];
const ocDistLabel = (v) => (OC_DIST_OPTIONS.find(o => o.v === v) || OC_DIST_OPTIONS[0]).l;

const OC_STEPS = [
  { id: 'company',  label: 'Company',   th: 'ข้อมูลลูกค้า' },
  { id: 'features', label: 'Call flow', th: 'ตั้งค่าบริการ' },
  { id: 'ivr',      label: 'IVR menu',  th: 'ผังเมนู IVR' },
  { id: 'review',   label: 'Review',    th: 'ตรวจสอบและส่ง' },
];

const OC_SEED = {
  customerType: 'existing',
  companyId: null,
  company: null,
  contacts: [
    { name: '', role: '', email: '', phone: '', mobile: '', contactType: 'Primary' },
  ],
  activation: 'asap',
  sale: '',
  features: {
    ivrLayer: 'single',
    mainNumbers: ['', ''],
    chargingNumber: '',
    ivrMain: true,
    workingHours: '9:00 - 20:00 น.',
    startTime: '09:00',
    endTime: '20:00',
    allDay: false,
    agentNonOffice: true,
    voiceRecord: true,
    altCorpNumber: false,
    altNumbers: ['', '', ''],
    realNumber: false,
    realNumberDetail: '',
    productionHouse: false,
  },
  ivr: { office: [], nonOffice: [] },
  ivrAudio: { office: null, nonOffice: null },
};

const draftToApi = (draft) => ({
  customerType: draft.customerType,
  companyId: draft.companyId || null,
  companyData: draft.company || {},
  contacts: draft.contacts || [],
  activation: draft.activation,
  sale: draft.sale || '',
  features: draft.features,
  ivr: draft.ivr,
  ivrAudio: draft.ivrAudio || { office: null, nonOffice: null },
});

const isMobileNumber = (v) => /^0[689]\d{8}$/.test((v || '').replace(/[-\s]/g, ''));

const apiToDraft = (oc) => {
  const feats = { ...OC_SEED.features, ...oc.features };
  // Normalize mainNumbers to exactly 2 slots [primary, alternative]
  const mn = Array.isArray(feats.mainNumbers) ? feats.mainNumbers : [];
  feats.mainNumbers = [mn[0] || '', mn[1] || ''];
  return {
    customerType: oc.customerType,
    companyId: oc.companyId,
    company: oc.companyData && Object.keys(oc.companyData).length ? oc.companyData : null,
    contacts: oc.contacts && oc.contacts.length ? oc.contacts : [{ name: '', role: '', email: '', phone: '', mobile: '', contactType: 'Primary' }],
    activation: oc.activation || 'asap',
    sale: oc.sale || '',
    features: feats,
    ivr: oc.ivr && (oc.ivr.office || oc.ivr.nonOffice) ? oc.ivr : { office: [], nonOffice: [] },
    ivrAudio: oc.ivrAudio || { office: null, nonOffice: null },
  };
};

const OneCallOrderView = ({ onBack, onComplete, prefill, orderId }) => {
  const [step, setStep] = useState(0);
  const [draft, setDraft] = useState(() => {
    const base = JSON.parse(JSON.stringify(OC_SEED));
    if (prefill?.companyId) {
      const allContacts = window.CONTACTS || CONTACTS || {};
      const existing = allContacts[prefill.companyId] || {};
      base.companyId = prefill.companyId;
      base.company = prefill.company;
      base.customerType = 'existing';
      base.contacts = [{
        name: existing.name || '',
        role: existing.role || '',
        email: existing.email || '',
        phone: existing.phone || '',
        mobile: existing.mobile || '',
        contactType: existing.contactType || 'Primary',
      }];
    }
    return base;
  });
  const [draftId, setDraftId] = useState(null);
  const [orderNumber, setOrderNumber] = useState(null);
  const [saving, setSaving] = useState(false);

  // Load existing order by ID (from OC order list)
  useEffect(() => {
    if (!orderId) return;
    window.apiFetch(`/api/one-call-orders/${orderId}`)
      .then(r => r.json())
      .then(data => {
        if (!data.error) {
          setDraftId(data.id);
          setOrderNumber(data.orderNumber);
          setDraft(apiToDraft(data));
        }
      })
      .catch(() => {});
  }, []);

  // Load existing draft for this company if navigating from Provisioning
  useEffect(() => {
    if (!prefill?.companyId) return;
    window.apiFetch(`/api/one-call-orders?companyId=${prefill.companyId}&status=draft&limit=1`)
      .then(r => r.json())
      .then(data => {
        if (Array.isArray(data) && data.length > 0) {
          const oc = data[0];
          setDraftId(oc.id);
          setOrderNumber(oc.orderNumber);
          setDraft(apiToDraft(oc));
          showToast('โหลด draft ที่บันทึกไว้', { variant: 'info', detail: oc.orderNumber });
        }
      })
      .catch(() => {});
  }, []);

  const saveDraft = async () => {
    setSaving(true);
    try {
      const body = JSON.stringify(draftToApi(draft));
      if (!draftId) {
        const r = await window.apiFetch('/api/one-call-orders', { method: 'POST', body });
        if (!r.ok) throw new Error('Save failed');
        const data = await r.json();
        setDraftId(data.id);
        setOrderNumber(data.orderNumber);
        showToast('บันทึก draft แล้ว', { variant: 'success', detail: data.orderNumber });
      } else {
        await window.apiFetch(`/api/one-call-orders/${draftId}`, { method: 'PATCH', body });
        showToast('อัปเดต draft แล้ว', { variant: 'success' });
      }
    } catch (e) {
      showToast('บันทึกไม่สำเร็จ', { variant: 'error' });
    } finally {
      setSaving(false);
    }
  };

  const submitOrder = async () => {
    setSaving(true);
    try {
      let id = draftId;
      if (!id) {
        const r = await window.apiFetch('/api/one-call-orders', { method: 'POST', body: JSON.stringify(draftToApi(draft)) });
        if (!r.ok) throw new Error('Save failed');
        const data = await r.json();
        id = data.id;
        setDraftId(id);
        setOrderNumber(data.orderNumber);
      } else {
        await window.apiFetch(`/api/one-call-orders/${id}`, { method: 'PATCH', body: JSON.stringify(draftToApi(draft)) });
      }
      const sr = await window.apiFetch(`/api/one-call-orders/${id}/submit`, { method: 'POST' });
      if (!sr.ok) throw new Error('Submit failed');
      const submitted = await sr.json();
      showToast('ส่งใบสมัคร One Call เรียบร้อย', { variant: 'success', detail: `${submitted.orderNumber} · ${draft.company?.name || 'ลูกค้า'}` });
      onComplete && onComplete(submitted.id || id, submitted.orderNumber);
    } catch (e) {
      showToast('ส่งใบสมัครไม่สำเร็จ', { variant: 'error' });
    } finally {
      setSaving(false);
    }
  };

  const next = () => setStep(s => Math.min(s + 1, OC_STEPS.length - 1));
  const prev = () => setStep(s => Math.max(s - 1, 0));

  const canContinue = (() => {
    if (step === 1) {
      const f = draft.features;
      return isMobileNumber(f.chargingNumber) && (f.mainNumbers[0] || '').trim().length > 0;
    }
    return true;
  })();

  return (
    <>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11.5, color: 'var(--ink-3)', marginBottom: 10 }}>
        <button onClick={onBack} style={ocLinkBtn}><Icon name="chevronLeft" size={11}/> Orders</button>
        <Icon name="chevron" size={9}/>
        <span>One Call order</span>
        {orderNumber && <><Icon name="chevron" size={9}/><span className="num" style={{ color: 'var(--ink-2)' }}>{orderNumber}</span></>}
      </div>

      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 16, marginBottom: 20 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <ProductGlyph productId="one_call" size={40}/>
          <div>
            <h1 style={{ fontSize: 22, fontWeight: 500, letterSpacing: '-0.01em', margin: '0 0 2px' }}>สมัครบริการ One Call</h1>
            <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>กรอกข้อมูลลูกค้าและออกแบบผัง Call Flow (IVR) สำหรับเบอร์กลางองค์กร</div>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <Button variant="ghost" icon="file" disabled={saving} onClick={saveDraft}>{saving ? 'กำลังบันทึก…' : (draftId ? 'Update draft' : 'Save draft')}</Button>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '220px 1fr', gap: 20 }}>
        {/* Step rail */}
        <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 4, padding: 12, alignSelf: 'flex-start', position: 'sticky', top: 76 }}>
          <div className="eyebrow" style={{ padding: '4px 8px 8px' }}>One Call setup</div>
          {OC_STEPS.map((s, i) => {
            const done = i < step; const active = i === step;
            return (
              <button key={s.id} onClick={() => done && setStep(i)} disabled={!done && !active}
                style={{
                  display: 'flex', alignItems: 'center', gap: 10, padding: '8px 10px', width: '100%', textAlign: 'left',
                  background: active ? 'var(--bg-2)' : 'transparent', border: 'none', borderRadius: 3,
                  cursor: done ? 'pointer' : 'default', fontFamily: 'Kanit, sans-serif', fontSize: 12.5,
                  color: active ? 'var(--ink)' : done ? 'var(--ink-2)' : 'var(--ink-3)', marginBottom: 2,
                }}>
                <span style={{
                  width: 20, height: 20, borderRadius: '50%',
                  background: done ? 'var(--positive)' : active ? 'var(--ink)' : 'var(--panel)',
                  border: done || active ? 'none' : '1.5px solid var(--line-3)',
                  color: '#fff', display: 'grid', placeItems: 'center', fontSize: 10.5, fontWeight: 600,
                  flexShrink: 0, fontFamily: 'IBM Plex Mono',
                }}>{done ? <Icon name="check" size={10}/> : i + 1}</span>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontWeight: active ? 500 : 400 }}>{s.label}</div>
                  <div style={{ fontSize: 10.5, color: 'var(--ink-3)' }}>{s.th}</div>
                </div>
              </button>
            );
          })}

          {/* Live call-flow mini preview */}
          <div style={{ marginTop: 14, paddingTop: 12, borderTop: '1px solid var(--line-2)' }}>
            <div className="eyebrow" style={{ padding: '0 8px 8px' }}>Call flow · office</div>
            <div style={{ padding: '0 8px', display: 'flex', flexDirection: 'column', gap: 6 }}>
              {!draft.features.ivrMain
                ? <div style={{ fontSize: 11, color: 'var(--ink-4)' }}>ไม่มี Call flow</div>
                : draft.ivr.office.length === 0
                  ? <div style={{ fontSize: 11, color: 'var(--ink-4)' }}>ยังไม่มีเมนู</div>
                  : draft.ivr.office.map(m => (
                    <div key={m.key} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11 }}>
                      <span className="num" style={{
                        width: 16, height: 16, borderRadius: 2, background: '#d97b2e20',
                        color: '#d97b2e', display: 'grid', placeItems: 'center', fontWeight: 600, fontSize: 10, flexShrink: 0,
                      }}>{m.key}</span>
                      <span style={{ color: 'var(--ink-2)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{m.dept || '—'}</span>
                    </div>
                  ))
              }
            </div>
          </div>
        </div>

        {/* Step body */}
        <div>
          <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 4, minHeight: 460 }}>
            {step === 0 && <OcCompanyStep draft={draft} setDraft={setDraft} fromProv={!!prefill?.companyId}/>}
            {step === 1 && <OcFeaturesStep draft={draft} setDraft={setDraft}/>}
            {step === 2 && <OcIvrStep draft={draft} setDraft={setDraft}/>}
            {step === 3 && <OcReviewStep draft={draft}/>}
          </div>

          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 12 }}>
            <Button variant="ghost" disabled={step === 0} onClick={prev} icon="chevronLeft">Back</Button>
            <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>
              Step <span className="num" style={{ color: 'var(--ink-2)' }}>{step + 1}</span> of <span className="num">{OC_STEPS.length}</span>
            </div>
            {step < OC_STEPS.length - 1
              ? <Button variant="primary" disabled={!canContinue} onClick={next} iconRight="chevron">Continue</Button>
              : <Button variant="accent" icon="check" disabled={saving} onClick={submitOrder}>
                  {saving ? 'กำลังส่ง…' : 'Submit order'}
                </Button>}
          </div>
        </div>
      </div>
    </>
  );
};

const ocLinkBtn = {
  background: 'none', border: 'none', cursor: 'pointer', color: 'var(--ink-3)',
  fontFamily: 'Kanit, sans-serif', fontSize: 11.5, padding: 0,
  display: 'inline-flex', alignItems: 'center', gap: 4,
};
const ocIconBtn = {
  width: 28, height: 28, padding: 0, background: 'var(--panel)', border: '1px solid var(--line)',
  borderRadius: 3, cursor: 'pointer', color: 'var(--ink-2)', display: 'grid', placeItems: 'center', flexShrink: 0,
};
const ocAddBtn = {
  display: 'inline-flex', alignItems: 'center', gap: 5, padding: '6px 10px',
  background: 'transparent', border: 'none', cursor: 'pointer',
  fontFamily: 'Kanit, sans-serif', fontSize: 11.5, color: '#d97b2e', fontWeight: 500,
};

// ---------- Step 1: Company ----------
const OcCompanyStep = ({ draft, setDraft, fromProv = false }) => {
  const [q, setQ] = useState('');
  const isNew = draft.customerType === 'new';
  const companies = window.COMPANIES || COMPANIES || [];
  const filtered = companies.filter(c => !q || c.name.toLowerCase().includes(q.toLowerCase()) || (c.taxId || '').includes(q));

  const pick = (co) => {
    if (isNew) return;
    const allContacts = window.CONTACTS || CONTACTS || {};
    const existing = allContacts[co.id] || {};
    setDraft(d => ({
      ...d,
      companyId: co.id,
      company: co,
      contacts: [{
        name: existing.name || '',
        role: existing.role || '',
        email: existing.email || '',
        phone: existing.phone || '',
        mobile: existing.mobile || '',
        contactType: existing.contactType || 'Primary',
      }],
    }));
  };

  const updCt = (i, k, v) => setDraft(d => ({
    ...d,
    contacts: d.contacts.map((c, idx) => idx === i ? { ...c, [k]: v } : c),
  }));
  const addContact = () => setDraft(d => ({
    ...d,
    contacts: [...d.contacts, { name: '', role: '', email: '', phone: '', mobile: '', contactType: 'Technical' }],
  }));
  const removeContact = (i) => setDraft(d => ({
    ...d,
    contacts: d.contacts.filter((_, idx) => idx !== i),
  }));
  const updCo = (k, v) => setDraft(d => ({ ...d, company: { ...(d.company || {}), [k]: v } }));

  return (
    <div style={{ padding: '24px 28px' }}>
      <OcStepHeader n={1} label="Company information" th="ข้อมูลลูกค้า"
        desc="ค้นหาบริษัทจาก customer database หรือเพิ่มลูกค้าใหม่ พร้อมข้อมูลผู้ติดต่อ"/>

      {!fromProv && (
        <>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18, marginTop: 18 }}>
            <Field label="ค้นหาลูกค้า / Tax ID">
              <div style={{ position: 'relative' }}>
                <span style={{ position: 'absolute', left: 9, top: '50%', transform: 'translateY(-50%)', color: isNew ? 'var(--line-3)' : 'var(--ink-3)' }}>
                  <Icon name="search" size={13}/>
                </span>
                <input value={q} onChange={e => setQ(e.target.value)}
                  disabled={isNew}
                  placeholder="ชื่อบริษัท หรือเลขประจำตัวผู้เสียภาษี…"
                  style={{ ...inputStyle, paddingLeft: 30, opacity: isNew ? 0.4 : 1, cursor: isNew ? 'not-allowed' : 'text' }}/>
              </div>
            </Field>
            <Field label="ประเภทลูกค้า">
              <Select value={draft.customerType} onChange={e => setDraft(d => ({
                ...d, customerType: e.target.value,
                companyId: null,
                company: e.target.value === 'new' ? {} : null,
                contacts: [{ name: '', role: '', email: '', phone: '', mobile: '', contactType: 'Primary' }],
              }))}>
                <option value="existing">Existing customer</option>
                <option value="new">New customer (สร้างใหม่)</option>
              </Select>
            </Field>
          </div>

          <div style={{ marginTop: 18, position: 'relative' }}>
            <div className="eyebrow" style={{ marginBottom: 8, color: isNew ? 'var(--ink-4)' : 'var(--ink-3)' }}>
              Customer matches · {filtered.length} results
            </div>
            <div style={{
              border: `1px solid ${isNew ? 'var(--line-2)' : 'var(--line)'}`,
              borderRadius: 3, maxHeight: 220, overflowY: 'auto',
              opacity: isNew ? 0.4 : 1, pointerEvents: isNew ? 'none' : 'auto',
            }}>
              {filtered.map((co, i) => {
                const sel = !isNew && draft.companyId === co.id;
                return (
                  <div key={co.id} onClick={() => pick(co)} style={{
                    padding: '10px 14px',
                    borderBottom: i === filtered.length - 1 ? 'none' : '1px solid var(--line-2)',
                    background: sel ? 'var(--bg-2)' : 'transparent', cursor: isNew ? 'default' : 'pointer',
                    display: 'grid', gridTemplateColumns: '32px 1fr auto auto', gap: 12, alignItems: 'center',
                  }}
                  onMouseEnter={e => !sel && !isNew && (e.currentTarget.style.background = 'var(--bg-hover)')}
                  onMouseLeave={e => !sel && !isNew && (e.currentTarget.style.background = 'transparent')}>
                    <Avatar name={co.name} size={28} square/>
                    <div>
                      <div style={{ fontWeight: 500, fontSize: 13 }}>{co.name}</div>
                      <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{co.sector} · {co.province}</div>
                    </div>
                    <div className="num" style={{ fontSize: 11, color: 'var(--ink-3)' }}>{co.taxId}</div>
                    <div style={{ width: 18, display: 'grid', placeItems: 'center' }}>
                      {sel ? <Icon name="check" size={14} color="var(--positive)"/> : null}
                    </div>
                  </div>
                );
              })}
            </div>
            {isNew && (
              <div style={{
                position: 'absolute', inset: 0, top: 24, display: 'flex', alignItems: 'center', justifyContent: 'center',
                borderRadius: 3, pointerEvents: 'none',
              }}>
                <div style={{ background: 'var(--panel)', border: '1px solid var(--line-2)', borderRadius: 3, padding: '6px 14px', fontSize: 12, color: 'var(--ink-3)', display: 'flex', alignItems: 'center', gap: 6 }}>
                  <Icon name="lock" size={12}/>
                  New customer — กรอกข้อมูลด้านล่าง
                </div>
              </div>
            )}
          </div>
        </>
      )}

      {!isNew && draft.company && (
        <div style={{ marginTop: 14, padding: 14, background: 'var(--bg-2)', borderRadius: 3, display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
          <DefStack label="Company" value={draft.company.name}/>
          <DefStack label="Tax ID" value={<span className="num">{draft.company.taxId}</span>}/>
          <DefStack label="Sector" value={draft.company.sector}/>
          <DefStack label="Size" value={`${draft.company.size} emp.`}/>
        </div>
      )}

      {isNew && (
        <div style={{ marginTop: 20, padding: '16px 20px', background: 'var(--bg-2)', borderRadius: 4, border: '1px solid var(--line)' }}>
          <div className="eyebrow" style={{ marginBottom: 14, display: 'flex', alignItems: 'center', gap: 6 }}>
            <Icon name="building" size={11}/>
            ข้อมูลบริษัทลูกค้าใหม่ · New company information
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <Field label="ชื่อบริษัท" required>
              <TextInput placeholder="บริษัท / ห้างหุ้นส่วน / องค์กร"
                value={draft.company?.name || ''}
                onChange={e => updCo('name', e.target.value)}/>
            </Field>
            <Field label="เลขประจำตัวผู้เสียภาษี (Tax ID)" required>
              <TextInput placeholder="13 หลัก" style={{ fontFamily: 'IBM Plex Mono' }}
                value={draft.company?.taxId || ''}
                onChange={e => updCo('taxId', e.target.value)}/>
            </Field>
            <Field label="ประเภทธุรกิจ (Sector)">
              <Select value={draft.company?.sector || ''} onChange={e => updCo('sector', e.target.value)}>
                <option value="">— เลือกประเภท —</option>
                {(typeof SECTORS !== 'undefined' ? SECTORS : []).map(s => <option key={s} value={s}>{s}</option>)}
              </Select>
            </Field>
            <Field label="จังหวัด (Province)">
              <TextInput placeholder="กรุงเทพมหานคร / จังหวัด"
                value={draft.company?.province || ''}
                onChange={e => updCo('province', e.target.value)}/>
            </Field>
          </div>
        </div>
      )}

      <div style={{ marginTop: 22, borderTop: '1px solid var(--line-2)', paddingTop: 18 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
          <div className="eyebrow" style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <Icon name="user" size={11}/>
            ผู้ติดต่อ · Contacts ({draft.contacts?.length || 1})
          </div>
          <button onClick={addContact} style={ocAddBtn}>
            <Icon name="plus" size={11}/> เพิ่มผู้ติดต่อ
          </button>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {(draft.contacts || []).map((ct, i) => (
            <div key={i} style={{
              padding: '14px 16px', borderRadius: 4,
              border: i === 0 ? '1px solid var(--line)' : '1px dashed var(--line-3)',
              background: i === 0 ? 'var(--panel)' : 'var(--bg)',
            }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
                <span style={{
                  fontSize: 10, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.06em',
                  padding: '2px 8px', borderRadius: 2,
                  background: i === 0 ? 'var(--ink)' : 'var(--bg-3)',
                  color: i === 0 ? '#fff' : 'var(--ink-3)',
                }}>
                  {i === 0 ? 'Contact 1 · Primary' : `Contact ${i + 1}`}
                </span>
                {i > 0 && (
                  <button onClick={() => removeContact(i)} style={{
                    background: 'none', border: 'none', cursor: 'pointer',
                    color: 'var(--negative)', padding: '2px 6px', display: 'flex', alignItems: 'center', gap: 4,
                    fontFamily: 'Kanit, sans-serif', fontSize: 11,
                  }}>
                    <Icon name="close" size={11}/> ลบ
                  </button>
                )}
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                <Field label="ชื่อ-นามสกุล" required={i === 0}>
                  <TextInput value={ct.name || ''} onChange={e => updCt(i, 'name', e.target.value)}/>
                </Field>
                <Field label="ตำแหน่ง">
                  <TextInput value={ct.role || ''} onChange={e => updCt(i, 'role', e.target.value)}/>
                </Field>
                <Field label="ประเภทผู้ติดต่อ · Contact type" required>
                  <Select value={ct.contactType || 'Primary'} onChange={e => updCt(i, 'contactType', e.target.value)}>
                    <option value="Primary">Primary</option>
                    <option value="Executive">Executive</option>
                    <option value="Accounting">Accounting</option>
                    <option value="Sales">Sales</option>
                    <option value="Technical">Technical</option>
                  </Select>
                </Field>
                <Field label="อีเมล" required={i === 0} hint={i === 0 ? 'ใช้สำหรับ activation link' : ''}>
                  <TextInput type="email" value={ct.email || ''} onChange={e => updCt(i, 'email', e.target.value)}/>
                </Field>
                <Field label="เบอร์มือถือ">
                  <TextInput value={ct.mobile || ''} onChange={e => updCt(i, 'mobile', e.target.value)} style={{ fontFamily: 'IBM Plex Mono' }}/>
                </Field>
                <Field label="เบอร์โทรที่ทำงาน">
                  <TextInput value={ct.phone || ''} onChange={e => updCt(i, 'phone', e.target.value)} style={{ fontFamily: 'IBM Plex Mono' }}/>
                </Field>
              </div>
            </div>
          ))}
        </div>
      </div>

      <div style={{ marginTop: 22, borderTop: '1px solid var(--line-2)', paddingTop: 18 }}>
        <div className="eyebrow" style={{ marginBottom: 14 }}>One Call order details</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
          <Field label="วันที่เริ่มใช้งาน · Activation date" required hint="One Call SLA ปกติ 3 วันทำการ">
            <DatePicker value={draft.activation} onChange={v => setDraft(d => ({ ...d, activation: v }))}
              recommended={new Date(Date.now() + 4 * 86400000)}
              recommendedLabel="ตาม SLA One Call 3 วันทำการ"
              asapLabel="เริ่มทันทีตาม SLA"/>
          </Field>
          <Field label="ชื่อเซลล์ · Sale name" hint="Optional">
            <TextInput value={draft.sale || ''} onChange={e => setDraft(d => ({ ...d, sale: e.target.value }))}/>
          </Field>
        </div>
      </div>
    </div>
  );
};

// ---------- Step 2: Features ----------
const OcFeaturesStep = ({ draft, setDraft }) => {
  const f = draft.features;
  const [confirmIvrOff, setConfirmIvrOff] = useState(false);
  const upd = (k, v) => setDraft(d => ({ ...d, features: { ...d.features, [k]: v } }));
  const setMainNumber = (i, v) => upd('mainNumbers', f.mainNumbers.map((n, j) => j === i ? v : n));
  const addMainNumber = () => upd('mainNumbers', f.mainNumbers.length < 3 ? [...f.mainNumbers, ''] : f.mainNumbers);
  const removeMainNumber = (i) => upd('mainNumbers', f.mainNumbers.filter((_, j) => j !== i));

  const handleIvrMainChange = (v) => {
    if (v === false && draft.ivr.office.length > 0) {
      setConfirmIvrOff(true); // show modal
    } else {
      upd('ivrMain', v);
    }
  };

  const confirmIvrOff_apply = () => {
    const firstMenu = draft.ivr.office[0] || { lines: [{ phone: '', ext: '' }] };
    setDraft(d => ({
      ...d,
      features: { ...d.features, ivrMain: false },
      ivr: {
        office: [{ key: '*', dept: 'โทรตรงเบอร์ปลายทาง', dist: 'linear', lines: firstMenu.lines }],
        nonOffice: [],
      },
    }));
    setConfirmIvrOff(false);
  };

  const setWorkTime = (which, v) => {
    const start = which === 'start' ? v : f.startTime;
    const end = which === 'end' ? v : f.endTime;
    const fmt = (t) => { const [h, m] = t.split(':'); return parseInt(h) + ':' + m; };
    setDraft(d => ({ ...d, features: { ...d.features, startTime: start, endTime: end, workingHours: `${fmt(start)} - ${fmt(end)} น.` } }));
  };

  return (
    <div style={{ padding: '24px 28px' }}>
      <OcStepHeader n={2} label="Call flow settings" th="ตั้งค่าบริการ"
        desc="กำหนดเบอร์แม่และฟีเจอร์การรับสายตามที่ลูกค้าต้องการ"/>

      <div style={{ marginTop: 18, border: '1px solid var(--line)', borderRadius: 6, padding: '16px 18px', display: 'flex', flexDirection: 'column', gap: 14, background: 'var(--bg-1)' }}>
        <div className="eyebrow" style={{ fontSize: 10, letterSpacing: '0.06em', color: 'var(--ink-3)', marginBottom: -4 }}>หมายเลขโทรศัพท์ · Phone Numbers</div>

        <Field label="เบอร์ที่คิดค่าบริการ · Charging Number" required hint="หมายเลขมือถือที่ใช้คิดค่าบริการ One Call · ใส่ได้ 1 เบอร์">
          <TextInput
            value={f.chargingNumber || ''}
            onChange={e => upd('chargingNumber', e.target.value.replace(/[^\d-]/g, ''))}
            style={{ fontFamily: 'IBM Plex Mono', borderColor: f.chargingNumber && !isMobileNumber(f.chargingNumber) ? 'var(--negative)' : undefined }}
            placeholder="เช่น 0812345678"
            maxLength={12}/>
          {f.chargingNumber && !isMobileNumber(f.chargingNumber)
            ? <div style={{ fontSize: 11, color: 'var(--negative)', marginTop: 4 }}>ต้องเป็นหมายเลขมือถือ 10 หลัก (06x / 08x / 09x)</div>
            : <div style={{ fontSize: 11, color: 'var(--ink-4)', marginTop: 4 }}>หมายเลขมือถือที่ใช้คิดค่าบริการ One Call · ใส่ได้ 1 เบอร์</div>
          }
        </Field>

        <Field label="เบอร์แม่หลัก · Primary Number" required hint="เบอร์กลางหลักที่ลูกค้าใช้รับสายเข้าองค์กร">
          <TextInput
            value={f.mainNumbers[0] || ''}
            onChange={e => setMainNumber(0, e.target.value)}
            style={{ fontFamily: 'IBM Plex Mono' }}
            placeholder="เช่น 02-096-6378"/>
        </Field>

        <Field label="เบอร์แม่รอง · Alternative Number" hint="เบอร์กลางสำรอง (ถ้ามี)">
          <TextInput
            value={f.mainNumbers[1] || ''}
            onChange={e => setMainNumber(1, e.target.value)}
            style={{ fontFamily: 'IBM Plex Mono' }}
            placeholder="เช่น 02-096-6379"/>
        </Field>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginTop: 16 }}>
        <Field label="ช่วงเวลาทำการ · Company working hours" required hint="เลือกเวลาเริ่มงานและเลิกงาน">
          <label style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 8, cursor: 'pointer', userSelect: 'none' }}>
            <input type="checkbox" checked={!!f.allDay} onChange={e => {
              const checked = e.target.checked;
              setDraft(d => ({ ...d, features: { ...d.features, allDay: checked,
                startTime: checked ? '00:00' : '09:00',
                endTime: checked ? '23:59' : '20:00',
                workingHours: checked ? '00:00 - 23:59 น.' : '9:00 - 20:00 น.',
                agentNonOffice: checked ? false : d.features.agentNonOffice,
              }}));
            }} style={{ width: 14, height: 14, cursor: 'pointer', accentColor: 'var(--accent-2)' }}/>
            <span style={{ fontSize: 12.5, color: 'var(--ink-2)', fontWeight: 500 }}>ทำการ 24 ชม.</span>
          </label>
          {!f.allDay && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <Select value={f.startTime} onChange={e => setWorkTime('start', e.target.value)} style={{ fontFamily: 'IBM Plex Mono' }}>
                {OC_TIME_OPTIONS.map(t => <option key={t} value={t}>{t} น.</option>)}
              </Select>
              <span style={{ color: 'var(--ink-3)', fontSize: 12, flexShrink: 0 }}>ถึง</span>
              <Select value={f.endTime} onChange={e => setWorkTime('end', e.target.value)} style={{ fontFamily: 'IBM Plex Mono' }}>
                {OC_TIME_OPTIONS.map(t => <option key={t} value={t}>{t} น.</option>)}
              </Select>
            </div>
          )}
          {f.allDay && (
            <div style={{ fontSize: 12, color: 'var(--ink-3)', fontFamily: 'IBM Plex Mono' }}>00:00 – 23:59 น.</div>
          )}
        </Field>
      </div>

      <div style={{ marginTop: 20 }}>
        <div className="eyebrow" style={{ marginBottom: 8 }}>Features · ฟีเจอร์การรับสาย</div>
        <div style={{ border: '1px solid var(--line)', borderRadius: 4, overflow: 'hidden' }}>
          <OcToggleRow th="Layer ของระบบ IVR" en="IVR layer structure" mode="layer"
            hint="Single = 1 ชั้นเมนู · Multi = หลายชั้นเมนูซ้อนกัน"
            value={f.ivrLayer} onChange={v => upd('ivrLayer', v)}/>
          <OcToggleRow th="มีเสียงตอบรับอัตโนมัติ (IVR) สำหรับเบอร์แม่" en="IVR for the main number" mode="have"
            value={f.ivrMain} onChange={handleIvrMainChange}/>
          <OcToggleRow th="มีพนักงานรับสายช่วงนอกเวลาทำการ" en="Agent to pick up calls during non-office hours" mode="have"
            value={f.agentNonOffice} onChange={v => upd('agentNonOffice', v)} disabled={!!f.allDay}/>
          <OcToggleRow th="ต้องการบันทึกเสียงการสนทนา" en="Voice recording feature"
            value={f.voiceRecord} onChange={v => upd('voiceRecord', v)} last/>

        </div>
      </div>

      {/* Confirmation modal — IVR off when menus exist */}
      {confirmIvrOff && (
        <div style={{
          position: 'fixed', inset: 0, zIndex: 900,
          background: 'rgba(0,0,0,0.45)', display: 'flex', alignItems: 'center', justifyContent: 'center',
        }} onClick={() => setConfirmIvrOff(false)}>
          <div onClick={e => e.stopPropagation()} style={{
            background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 6,
            padding: '24px 28px', maxWidth: 420, width: '90%',
            boxShadow: '0 8px 32px rgba(0,0,0,0.2)',
          }}>
            <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, marginBottom: 16 }}>
              <div style={{ width: 36, height: 36, borderRadius: '50%', background: '#fef9c3', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
                <Icon name="warning" size={18} color="#854d0e"/>
              </div>
              <div>
                <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 6 }}>แก้ไข Call Flow Menu</div>
                <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.6 }}>
                  มีการกำหนด Call Flow menu ไว้แล้ว <strong>{draft.ivr.office.length} เมนู</strong><br/>
                  การปิด IVR จะ<strong>แก้ไข Call Flow ให้เหลือเพียง menu แรกเท่านั้น</strong> และอัปเดตให้เป็นโหมดโอนสายตรง
                </div>
              </div>
            </div>
            <div style={{ padding: '12px 14px', background: 'var(--bg-2)', borderRadius: 4, border: '1px solid var(--line-2)', fontSize: 12, color: 'var(--ink-2)', marginBottom: 20 }}>
              <div style={{ fontFamily: 'IBM Plex Mono', color: 'var(--ink-3)', marginBottom: 4, fontSize: 11 }}>จะถูกอัปเดตเป็น</div>
              <div>กด <strong style={{ fontFamily: 'IBM Plex Mono' }}>*</strong> · โทรตรงเบอร์ปลายทาง · Linear</div>
              <div style={{ color: 'var(--ink-3)', marginTop: 2, fontSize: 11 }}>เบอร์ปลายทางจากเมนูแรกจะถูกเก็บไว้</div>
            </div>
            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
              <button onClick={() => setConfirmIvrOff(false)} style={{
                padding: '8px 18px', border: '1px solid var(--line)', borderRadius: 4,
                background: 'transparent', cursor: 'pointer', fontFamily: 'Kanit, sans-serif', fontSize: 13, color: 'var(--ink-2)',
              }}>ยกเลิก</button>
              <button onClick={confirmIvrOff_apply} style={{
                padding: '8px 18px', border: 'none', borderRadius: 4,
                background: 'var(--ink)', color: '#fff', cursor: 'pointer',
                fontFamily: 'Kanit, sans-serif', fontSize: 13, fontWeight: 500,
              }}>ยืนยัน</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

const OcToggleRow = ({ th, en, hint, value, onChange, last, mode = 'want', disabled = false }) => {
  const opts = mode === 'have'
    ? [{ v: true, l: 'มี' }, { v: false, l: 'ไม่มี' }]
    : mode === 'layer'
    ? [{ v: 'single', l: 'Single' }, { v: 'multi', l: 'Multi' }]
    : [{ v: true, l: 'ต้องการ' }, { v: false, l: 'ไม่ต้องการ' }];
  return (
  <div style={{
    padding: '12px 16px', borderBottom: last ? 'none' : '1px solid var(--line-2)',
    display: 'flex', alignItems: 'center', gap: 14,
    opacity: disabled ? 0.45 : 1, pointerEvents: disabled ? 'none' : 'auto',
  }}>
    <div style={{ flex: 1 }}>
      <div style={{ fontSize: 12.5, fontWeight: 500 }}>{th}</div>
      <div style={{ fontSize: 10.5, color: 'var(--ink-3)' }}>{en}{hint ? ` · ${hint}` : ''}</div>
    </div>
    <div style={{ display: 'inline-flex', background: 'var(--bg-3)', padding: 2, borderRadius: 3 }}>
      {opts.map(o => {
        const active = value === o.v;
        const bgActive = mode === 'layer' ? 'var(--ink)' : (o.v === true ? 'var(--positive)' : 'var(--panel)');
        const colorActive = mode === 'layer' ? '#fff' : (o.v === true ? '#fff' : 'var(--ink)');
        return (
          <button key={String(o.v)} onClick={() => onChange(o.v)} style={{
            padding: '4px 14px', border: 'none', borderRadius: 2, cursor: 'pointer',
            fontFamily: 'Kanit, sans-serif', fontSize: 12, whiteSpace: 'nowrap',
            background: active ? bgActive : 'transparent',
            color: active ? colorActive : 'var(--ink-3)',
            fontWeight: active ? 500 : 400,
            boxShadow: active && o.v === false ? 'var(--shadow-segment)' : 'none',
          }}>{o.l}</button>
        );
      })}
    </div>
  </div>
  );
};

// ---------- Step 3: IVR builder ----------
const DIRECT_ROUTE_MENU = { key: '*', dept: 'เบอร์ตรง', dist: 'linear', lines: [{ phone: '', ext: '' }] };

const OcIvrStep = ({ draft, setDraft }) => {
  const [mode, setMode] = useState('office');
  const [xlsxError, setXlsxError] = useState('');
  const noIvr = !draft.features.ivrMain; // "ไมมีเสียงตอบรับ IVR"
  const menus = draft.ivr[mode];
  const officeFileRef = React.useRef(null);
  const nonOfficeFileRef = React.useRef(null);
  const xlsxRef = React.useRef(null);
  const fileRef = mode === 'office' ? officeFileRef : nonOfficeFileRef;
  const audioFile = (draft.ivrAudio || {})[mode];

  const handleXlsxUpload = (e) => {
    const file = e.target.files[0];
    if (!file) return;
    e.target.value = '';
    setXlsxError('');
    const reader = new FileReader();
    reader.onload = (ev) => {
      try {
        const XLSX = window.XLSX;
        if (!XLSX) { setXlsxError('ไม่พบ SheetJS library'); return; }
        const wb = XLSX.read(new Uint8Array(ev.target.result), { type: 'array' });
        const ws = wb.Sheets[wb.SheetNames[0]];
        const rows = XLSX.utils.sheet_to_json(ws, { defval: '' });
        // Normalize column names (case-insensitive, trim)
        const grouped = {};
        rows.forEach(row => {
          const keys = Object.keys(row);
          const menuCol = keys.find(k => /ivr.*menu|menu/i.test(k));
          const phoneCol = keys.find(k => /mobile|phone|number|เบอร์/i.test(k));
          const extCol = keys.find(k => /ext/i.test(k));
          if (!menuCol) return;
          const menuKey = String(row[menuCol] || '').trim();
          if (!menuKey) return;
          if (!grouped[menuKey]) grouped[menuKey] = [];
          grouped[menuKey].push({
            phone: String(row[phoneCol] || '').trim(),
            ext: String(row[extCol] || '').trim(),
          });
        });
        const keys = Object.keys(grouped);
        if (keys.length === 0) { setXlsxError('ไม่พบข้อมูล IVR ในไฟล์ กรุณาตรวจสอบ header: IVR Menu, Mobile Number, Extension'); return; }
        const newMenus = keys.map(k => ({
          key: k,
          dept: '',
          dist: 'linear',
          lines: grouped[k].length > 0 ? grouped[k] : [{ phone: '', ext: '' }],
        }));
        setMenus(newMenus);
      } catch (err) {
        setXlsxError('อ่านไฟล์ไม่ได้: ' + err.message);
      }
    };
    reader.readAsArrayBuffer(file);
  };

  // When ivrMain=false, auto-seed office with the direct-route card if empty
  useEffect(() => {
    if (noIvr && draft.ivr.office.length === 0) {
      setDraft(d => ({ ...d, ivr: { ...d.ivr, office: [{ ...DIRECT_ROUTE_MENU }] } }));
    }
  }, [noIvr]);

  const setAudioFile = (file) => setDraft(d => ({ ...d, ivrAudio: { ...(d.ivrAudio || {}), [mode]: file ? { name: file.name, size: file.size } : null } }));

  const setMenus = (newMenus) => setDraft(d => ({ ...d, ivr: { ...d.ivr, [mode]: newMenus } }));
  const updMenu = (i, patch) => setMenus(menus.map((m, j) => j === i ? { ...m, ...patch } : m));
  const addMenu = () => {
    const usedKeys = menus.map(m => m.key);
    const nextKey = ['0','1','2','3','4','5','6','7','8','9'].find(k => !usedKeys.includes(k)) || '#';
    setMenus([...menus, { key: nextKey, dept: '', dist: 'linear', lines: [{ phone: '', ext: '' }] }]);
  };
  const removeMenu = (i) => setMenus(menus.filter((_, j) => j !== i));
  const addLine = (mi) => updMenu(mi, { lines: [...menus[mi].lines, { phone: '', ext: '' }] });
  const updLine = (mi, li, patch) => updMenu(mi, { lines: menus[mi].lines.map((l, j) => j === li ? { ...l, ...patch } : l) });
  const removeLine = (mi, li) => updMenu(mi, { lines: menus[mi].lines.filter((_, j) => j !== li) });

  return (
    <div style={{ padding: '24px 28px' }}>
      <OcStepHeader n={3} label="IVR menu (Call Flow)" th="ผังเมนู IVR — Layer 1"
        desc="ออกแบบเมนูที่ผู้โทรจะได้ยิน — กดเลขเพื่อเข้าแต่ละแผนก พร้อมกำหนดวิธีกระจายสายและเบอร์ปลายทาง"/>

      {/* Mode tabs — hide when no IVR (direct routing only) */}
      {!noIvr && (
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 16, marginBottom: 14 }}>
          <Segmented options={[
            { value: 'office',    label: `เวลาทำการ · Office (${draft.ivr.office.length})` },
            { value: 'nonOffice', label: `นอกเวลา · Non-office (${draft.ivr.nonOffice.length})`, disabled: !!draft.features.allDay },
          ]} value={mode} onChange={v => { if(!(v === 'nonOffice' && draft.features.allDay)) setMode(v); }}/>
          <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>
            {mode === 'office' ? draft.features.workingHours : 'นอกช่วงเวลาทำการ'}
          </div>
        </div>
      )}

      {/* Audio upload — only when IVR enabled */}
      {draft.features.ivrMain && (
        <div style={{ marginBottom: 14 }}>
          <input ref={officeFileRef} type="file" accept=".wav,audio/wav" style={{ display: 'none' }}
            onChange={e => { if(mode==='office' && e.target.files[0]) setAudioFile(e.target.files[0]); }}/>
          <input ref={nonOfficeFileRef} type="file" accept=".wav,audio/wav" style={{ display: 'none' }}
            onChange={e => { if(mode==='nonOffice' && e.target.files[0]) setAudioFile(e.target.files[0]); }}/>
          <div style={{ border: '1px solid var(--line)', borderRadius: 4, background: 'var(--bg-2)', padding: '10px 14px' }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, flexWrap: 'wrap' }}>
              <div style={{ minWidth: 0 }}>
                <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink)', marginBottom: 2 }}>
                  ไฟล์เสียง IVR · {mode === 'office' ? 'เวลาทำการ' : 'นอกเวลา'}
                </div>
                <div style={{ fontSize: 11, color: audioFile ? 'var(--brand)' : 'var(--ink-3)', fontFamily: audioFile ? 'IBM Plex Mono' : 'inherit', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: 280 }}>
                  {audioFile ? '📎 ' + audioFile.name : 'อัปโหลดไฟล์เสียง WAV สำหรับ greeting · รับเฉพาะ .wav'}
                </div>
              </div>
              <div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
                {audioFile && (
                  <button onClick={() => setAudioFile(null)} style={{
                    fontFamily: 'Kanit, sans-serif', fontSize: 12, padding: '5px 10px',
                    background: 'none', color: 'var(--red)', border: '1px solid var(--red)',
                    borderRadius: 3, cursor: 'pointer',
                  }}>ลบ</button>
                )}
                <button onClick={() => fileRef.current?.click()} style={{
                  fontFamily: 'Kanit, sans-serif', fontSize: 12, padding: '5px 12px',
                  background: 'var(--accent-2)', color: '#fff',
                  border: 'none', borderRadius: 3, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 5,
                  whiteSpace: 'nowrap',
                }}>
                  <Icon name="upload" size={11}/> {audioFile ? 'เปลี่ยนไฟล์' : 'Upload WAV'}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Info banner for direct-route mode */}
      {noIvr && (
        <div style={{ marginTop: 16, marginBottom: 14, padding: '10px 14px', background: 'var(--bg-2)', border: '1px solid var(--line)', borderRadius: 4, display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, color: 'var(--ink-2)' }}>
          <Icon name="phone" size={13} color="var(--ink-3)"/>
          ระบบจะโอนสายตรงไปยังเบอร์ปลายทางโดยไม่มีเมนูเสียง IVR
        </div>
      )}

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {!noIvr && menus.length === 0 && (
          <div style={{ border: '1px dashed var(--line-3)', borderRadius: 4 }}>
            <Empty icon="pipeline" title="ยังไม่มีเมนู IVR" hint="คลิกปุ่มด้านล่างเพื่อเพิ่มเมนูแรก"/>
          </div>
        )}
        {menus.map((m, mi) => (
          <div key={mi} style={{ border: '1px solid var(--line)', borderRadius: 4, overflow: 'hidden' }}>
            {/* Card header — hidden in direct-route mode */}
            {!noIvr && (
              <div style={{ display: 'grid', gridTemplateColumns: 'auto 1fr auto auto', gap: 12, alignItems: 'center', padding: '12px 14px', background: 'var(--bg-2)', borderBottom: '1px solid var(--line-2)' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span style={{ fontSize: 11, color: 'var(--ink-3)' }}>กด</span>
                  <select value={m.key} onChange={e => updMenu(mi, { key: e.target.value })} style={{
                    ...inputStyle, width: 52, padding: '5px 4px', textAlign: 'center', fontFamily: 'IBM Plex Mono',
                    fontWeight: 600, fontSize: 14, color: '#d97b2e', cursor: 'pointer',
                  }}>
                    {['0','1','2','3','4','5','6','7','8','9','*','#'].map(k => <option key={k} value={k}>{k}</option>)}
                  </select>
                </div>
                <input value={m.dept} onChange={e => updMenu(mi, { dept: e.target.value })}
                  placeholder="ชื่อส่วน / แผนก เช่น ฝ่ายลูกค้าสัมพันธ์"
                  style={{ ...inputStyle, fontWeight: 500, fontSize: 13, background: 'var(--panel)' }}/>
                <select value={m.dist} onChange={e => updMenu(mi, { dist: e.target.value })} style={{
                  ...inputStyle, width: 'auto', padding: '6px 26px 6px 10px', fontSize: 12, cursor: 'pointer',
                }}>
                  {OC_DIST_OPTIONS.map(o => <option key={o.v} value={o.v}>{o.l} · {o.th}</option>)}
                </select>
                <button onClick={() => removeMenu(mi)} style={ocIconBtn} title="Remove menu"><Icon name="close" size={12}/></button>
              </div>
            )}

            <div style={{ padding: noIvr ? '12px 14px' : '4px 14px 12px' }}>
              <div style={{ display: 'grid', gridTemplateColumns: '28px 1fr 130px 36px', gap: 8, padding: '8px 0 6px' }}>
                <div className="eyebrow" style={{ fontSize: 9.5 }}>#</div>
                <div className="eyebrow" style={{ fontSize: 9.5 }}>เบอร์โทรศัพท์ · Phone</div>
                <div className="eyebrow" style={{ fontSize: 9.5 }}>Extension</div>
                <div></div>
              </div>
              {m.lines.map((ln, li) => (
                <div key={li} style={{ display: 'grid', gridTemplateColumns: '28px 1fr 130px 36px', gap: 8, alignItems: 'center', marginBottom: 5 }}>
                  <span className="num" style={{ fontSize: 11, color: 'var(--ink-3)', textAlign: 'center' }}>{li + 1}</span>
                  <TextInput value={ln.phone} onChange={e => updLine(mi, li, { phone: e.target.value })}
                    placeholder="เบอร์ปลายทาง" style={{ fontFamily: 'IBM Plex Mono', fontSize: 12, padding: '6px 9px' }}/>
                  <TextInput value={ln.ext} onChange={e => updLine(mi, li, { ext: e.target.value })}
                    placeholder="ext." style={{ fontFamily: 'IBM Plex Mono', fontSize: 12, padding: '6px 9px' }}/>
                  <button onClick={() => removeLine(mi, li)} disabled={m.lines.length === 1}
                    style={{ ...ocIconBtn, opacity: m.lines.length === 1 ? 0.3 : 1 }} title="Remove line"><Icon name="close" size={10}/></button>
                </div>
              ))}
              <button onClick={() => addLine(mi)} style={{ ...ocAddBtn, marginTop: 4 }}>
                <Icon name="plus" size={10}/> เพิ่มเบอร์ปลายทาง
              </button>
            </div>
          </div>
        ))}
      </div>

      {/* Add menu / Upload Excel — hidden in direct-route mode */}
      {!noIvr && (
        <div style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 8 }}>
          <input ref={xlsxRef} type="file" accept=".xlsx,.xls" style={{ display: 'none' }} onChange={handleXlsxUpload}/>
          <div style={{ display: 'flex', gap: 8 }}>
            <button onClick={addMenu} style={{
              flex: 1, padding: '11px', border: '1px dashed var(--line-3)',
              borderRadius: 4, background: 'var(--panel)', cursor: 'pointer',
              fontFamily: 'Kanit, sans-serif', fontSize: 12.5, color: 'var(--ink-2)',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            }}>
              <Icon name="plus" size={13}/> เพิ่มเมนู IVR
            </button>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
              <button onClick={() => xlsxRef.current?.click()} style={{
                padding: '11px 16px', border: '1px solid var(--line-3)',
                borderRadius: 4, background: 'var(--panel)', cursor: 'pointer',
                fontFamily: 'Kanit, sans-serif', fontSize: 12.5, color: 'var(--ink-2)',
                display: 'flex', alignItems: 'center', gap: 7, whiteSpace: 'nowrap',
              }}>
                <Icon name="upload" size={13}/> Upload IVR Template (.xlsx)
              </button>
              <a href="/assets/IVR-Template.xlsx" download="IVR-Template.xlsx" style={{
                fontSize: 11, color: 'var(--brand)', textAlign: 'center',
                textDecoration: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 4,
              }}>
                <Icon name="download" size={10}/> ดาวน์โหลด Template
              </a>
            </div>
          </div>
          {xlsxError && (
            <div style={{ fontSize: 11, color: 'var(--negative)', padding: '6px 10px', background: 'var(--negative-bg, #fff5f5)', borderRadius: 4, border: '1px solid var(--negative)' }}>
              {xlsxError}
            </div>
          )}
        </div>
      )}
    </div>
  );
};

// ---------- Step 4: Review ----------
const OcReviewStep = ({ draft }) => {
  const co = draft.company || {}; const ct = (draft.contacts || [])[0] || {}; const f = draft.features;
  const activeFeatures = [
    f.ivrMain && 'IVR เบอร์แม่',
    f.agentNonOffice && 'รับสายนอกเวลา',
    f.voiceRecord && 'บันทึกเสียง',
    f.altCorpNumber && 'เบอร์แม่หลายเบอร์',
  ].filter(Boolean);

  return (
    <div style={{ padding: '24px 28px' }}>
      <OcStepHeader n={4} label="Review & submit" th="ตรวจสอบและส่งใบสมัคร"
        desc="ตรวจสอบข้อมูลก่อนส่ง — ใบสมัครจะถูกส่งเข้า approval workflow ของ One Call (SLA 3 วันทำการ)"/>

      <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 14, marginTop: 18 }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <OcReviewBlock title="Company">
            <OcDef label="บริษัท" value={co.name || '—'}/>
            <OcDef label="Tax ID" value={<span className="num">{co.taxId || '—'}</span>}/>
            <OcDef label="Admin" value={ct.name || '—'}/>
            <OcDef label="Mobile" value={<span className="num">{ct.mobile || '—'}</span>}/>
            <OcDef label="Email" value={ct.email || '—'}/>
            <OcDef label="Activation" value={draft.activation === 'asap' ? 'ทันทีตาม SLA' : fmtDate(new Date(draft.activation))}/>
            <OcDef label="Sale" value={draft.sale || '—'}/>
          </OcReviewBlock>

          <OcReviewBlock title="Call flow settings">
            <OcDef label="Charging Number" value={<span className="num">{f.chargingNumber || '—'}</span>}/>
            <OcDef label="Primary Number" value={<span className="num">{f.mainNumbers[0] || '—'}</span>}/>
            {f.mainNumbers[1] && <OcDef label="Alternative Number" value={<span className="num">{f.mainNumbers[1]}</span>}/>}
            <OcDef label="เวลาทำการ" value={f.workingHours}/>
            <div style={{ gridColumn: '1 / -1', marginTop: 4 }}>
              <div style={{ fontSize: 10.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 6 }}>Features</div>
              <div style={{ display: 'flex', gap: 5, flexWrap: 'wrap' }}>
                {activeFeatures.length === 0 && <span style={{ fontSize: 12, color: 'var(--ink-4)' }}>ไม่มีฟีเจอร์เพิ่มเติม</span>}
                {activeFeatures.map(ft => (
                  <span key={ft} style={{
                    padding: '3px 9px', background: '#d97b2e14', color: '#d97b2e',
                    borderRadius: 2, fontSize: 11, fontWeight: 500,
                  }}>{ft}</span>
                ))}
              </div>
            </div>
          </OcReviewBlock>
        </div>

        {/* IVR preview */}
        <div style={{ background: 'var(--ink)', borderRadius: 4, padding: 18, alignSelf: 'flex-start' }}>
          <div style={{ fontSize: 10.5, color: '#d97b2e', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 500, marginBottom: 14 }}>Call flow preview</div>
          {!f.ivrMain ? (
            <div>
              <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.55)', marginBottom: 8 }}>โอนสายตรง ไปยังหมายเลข</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
                {(draft.ivr.office[0]?.lines || []).filter(l => l.phone).map((l, i) => (
                  <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span className="num" style={{
                      width: 16, height: 16, borderRadius: 2, background: 'rgba(255,255,255,0.12)',
                      color: 'rgba(255,255,255,0.5)', display: 'grid', placeItems: 'center', fontSize: 9, flexShrink: 0,
                    }}>{i + 1}</span>
                    <span className="num" style={{ fontSize: 12, color: '#fff', fontWeight: 500 }}>{l.phone}{l.ext ? ` ext.${l.ext}` : ''}</span>
                  </div>
                ))}
                {!(draft.ivr.office[0]?.lines || []).some(l => l.phone) && (
                  <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.3)' }}>—</div>
                )}
              </div>
            </div>
          ) : (
            ['office', 'nonOffice'].map(mode => (
              <div key={mode} style={{ marginBottom: 16 }}>
                <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.55)', marginBottom: 8, display: 'flex', alignItems: 'center', gap: 6 }}>
                  <Icon name={mode === 'office' ? 'clock' : 'bell'} size={11} color="rgba(255,255,255,0.55)"/>
                  {mode === 'office' ? `เวลาทำการ · ${f.workingHours}` : 'นอกเวลาทำการ'}
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                  {draft.ivr[mode].map(m => (
                    <div key={m.key} style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
                      <span className="num" style={{
                        width: 24, height: 24, borderRadius: 3, background: '#d97b2e', color: '#fff',
                        display: 'grid', placeItems: 'center', fontWeight: 600, fontSize: 13, flexShrink: 0,
                      }}>{m.key}</span>
                      <div style={{ flex: 1, minWidth: 0, paddingTop: 2 }}>
                        <div style={{ fontSize: 12, color: '#fff', fontWeight: 500 }}>{m.dept || '—'}</div>
                        <div style={{ fontSize: 10, color: 'rgba(255,255,255,0.5)' }}>
                          {m.dist === 'linear' ? 'Linear' : ocDistLabel(m.dist)} · <span className="num">{m.lines.length}</span> เบอร์
                        </div>
                      </div>
                    </div>
                  ))}
                  {draft.ivr[mode].length === 0 && <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.4)' }}>—</div>}
                </div>
              </div>
            ))
          )}
        </div>
      </div>
    </div>
  );
};

// ---------- helpers ----------
const OcStepHeader = ({ n, label, th, desc }) => (
  <div>
    <div className="eyebrow">Step {n} of 4</div>
    <h2 style={{ fontSize: 18, fontWeight: 500, letterSpacing: '-0.01em', margin: '4px 0 2px' }}>
      {label} <span style={{ fontSize: 14, color: 'var(--ink-3)', fontWeight: 400, marginLeft: 6 }}>{th}</span>
    </h2>
    {desc && <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{desc}</div>}
  </div>
);

const OcReviewBlock = ({ title, children }) => (
  <div style={{ background: 'var(--bg-2)', borderRadius: 3, padding: 14 }}>
    <div className="eyebrow" style={{ marginBottom: 8 }}>{title}</div>
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>{children}</div>
  </div>
);

const OcDef = ({ label, value }) => (
  <div>
    <div style={{ fontSize: 10.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{label}</div>
    <div style={{ fontSize: 12.5, color: 'var(--ink)', marginTop: 2 }}>{value}</div>
  </div>
);

// ─── One Call Order List ──────────────────────────────────────────────────────
const OC_STATUS_CFG = {
  draft:            { bg: 'var(--bg-3)',  color: 'var(--ink-3)',  label: 'Draft',             dot: null },
  pending:          { bg: '#dbeafe',      color: '#1d4ed8',       label: 'Submitted',         dot: '#2563eb' },
  submitted:        { bg: '#dbeafe',      color: '#1d4ed8',       label: 'Submitted',         dot: '#2563eb' },
  ready_to_process: { bg: '#fef9c3',      color: '#854d0e',       label: 'Ready to Process',  dot: '#ca8a04' },
  cancelled:        { bg: '#fee2e2',      color: '#b91c1c',       label: 'Cancelled',         dot: '#dc2626' },
  completed:        { bg: '#dcfce7',      color: '#15803d',       label: 'Completed',         dot: '#16a34a' },
  active:           { bg: '#dcfce7',      color: '#15803d',       label: 'Active',            dot: '#16a34a' },
};

const OC_STATUS_TRANSITIONS = {
  pending:          ['ready_to_process', 'cancelled'],
  submitted:        ['ready_to_process', 'cancelled'],
  ready_to_process: ['completed', 'cancelled'],
};

const OcStatusBadge = ({ status }) => {
  const cfg = OC_STATUS_CFG[status] || OC_STATUS_CFG.draft;
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, padding: '2px 8px', borderRadius: 3, fontSize: 11, fontWeight: 600, background: cfg.bg, color: cfg.color }}>
      {cfg.dot && <span style={{ width: 6, height: 6, borderRadius: '50%', background: cfg.dot, display: 'inline-block' }}/>}
      {cfg.label}
    </span>
  );
};

const OcStatusChanger = ({ orderId, status, onChanged }) => {
  const [open, setOpen] = React.useState(false);
  const [loading, setLoading] = React.useState(false);
  const [dropPos, setDropPos] = React.useState({ top: 0, right: 0, openUp: false });
  const btnRef = React.useRef(null);
  const allowed = OC_STATUS_TRANSITIONS[status] || [];

  React.useEffect(() => {
    if (!open) return;
    const handler = (e) => {
      if (!btnRef.current?.contains(e.target) && !e.target.closest('[data-oc-drop-root]')) {
        setOpen(false);
      }
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [open]);

  const handleOpen = () => {
    if (!btnRef.current) return;
    const r = btnRef.current.getBoundingClientRect();
    const dropH = 120; // estimated height
    const openUp = r.bottom + dropH > window.innerHeight - 8;
    setDropPos({
      top: openUp ? r.top + window.scrollY - dropH - 4 : r.bottom + window.scrollY + 4,
      right: window.innerWidth - r.right,
      openUp,
    });
    setOpen(o => !o);
  };

  const change = async (newStatus) => {
    setLoading(true);
    setOpen(false);
    try {
      const r = await window.apiFetch(`/api/one-call-orders/${orderId}/status`, {
        method: 'PATCH',
        body: JSON.stringify({ status: newStatus }),
      });
      if (!r.ok) throw new Error();
      onChanged && onChanged(orderId, newStatus);
      showToast('อัปเดต status เรียบร้อย', { variant: 'success', detail: OC_STATUS_CFG[newStatus]?.label });
    } catch {
      showToast('อัปเดต status ไม่สำเร็จ', { variant: 'error' });
    } finally {
      setLoading(false);
    }
  };

  if (allowed.length === 0) return <OcStatusBadge status={status}/>;

  const dropdown = open && ReactDOM.createPortal(
    <div data-oc-drop-root="1" style={{
      position: 'fixed', top: dropPos.top, right: dropPos.right, zIndex: 9999,
      background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 4,
      boxShadow: '0 4px 12px rgba(0,0,0,0.15)', minWidth: 170, overflow: 'hidden',
    }}>
      <div style={{ padding: '6px 10px 4px', fontSize: 10, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em', borderBottom: '1px solid var(--line-2)' }}>
        เปลี่ยนสถานะเป็น
      </div>
      {allowed.map(s => {
        const cfg = OC_STATUS_CFG[s];
        return (
          <button key={s} onClick={() => change(s)} style={{
            display: 'flex', alignItems: 'center', gap: 8, width: '100%',
            padding: '9px 12px', border: 'none', background: 'transparent',
            cursor: 'pointer', fontFamily: 'Kanit, sans-serif', fontSize: 12.5,
            color: 'var(--ink)', textAlign: 'left',
          }}
          onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-2)'}
          onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
            <span style={{ width: 8, height: 8, borderRadius: '50%', background: cfg?.dot || 'var(--ink-3)', flexShrink: 0 }}/>
            {cfg?.label || s}
          </button>
        );
      })}
    </div>,
    document.body
  );

  return (
    <div style={{ display: 'inline-block' }}>
      <button ref={btnRef}
        onClick={handleOpen}
        disabled={loading}
        style={{ background: 'none', border: 'none', padding: 0, cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 4 }}
      >
        <OcStatusBadge status={status}/>
        <span style={{ fontSize: 9, color: 'var(--ink-3)', opacity: loading ? 0.4 : 1 }}>▾</span>
      </button>
      {dropdown}
    </div>
  );
};

const OC_FILTER_OPTIONS = [
  { value: 'all',              label: 'ทุก Status' },
  { value: 'pending',          label: 'Submitted' },
  { value: 'ready_to_process', label: 'Ready to Process' },
  { value: 'cancelled',        label: 'Cancelled' },
  { value: 'completed',        label: 'Completed' },
  { value: 'draft',            label: 'Draft' },
];

const OcOrderListView = ({ onNew, onOpen }) => {
  const [orders, setOrders] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [filterStatus, setFilterStatus] = React.useState('all');

  React.useEffect(() => {
    window.apiFetch('/api/one-call-orders')
      .then(r => r.json())
      .then(data => { setOrders(Array.isArray(data) ? data : []); setLoading(false); })
      .catch(() => setLoading(false));
  }, []);

  const handleStatusChange = (id, newStatus) => {
    setOrders(prev => prev.map(o => o.id === id ? { ...o, status: newStatus } : o));
  };

  const fmtDate = (iso) => {
    if (!iso) return '—';
    return new Date(iso).toLocaleDateString('th-TH', { day: 'numeric', month: 'short', year: '2-digit' });
  };

  const filtered = filterStatus === 'all' ? orders : orders.filter(o => o.status === filterStatus);

  // count per status for badges
  const counts = orders.reduce((acc, o) => { acc[o.status] = (acc[o.status] || 0) + 1; return acc; }, {});

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 16 }}>
        <div>
          <div style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 4 }}>SOLUTIONS · ONE CALL</div>
          <h1 style={{ fontSize: 24, fontWeight: 500, letterSpacing: '-0.02em', margin: 0 }}>One Call Orders</h1>
          <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 3 }}>ใบสมัครบริการ One Call (IVR) ทั้งหมด</div>
        </div>
        <Button variant="primary" icon="plus" onClick={onNew}>New Order</Button>
      </div>

      {/* Status filter chips */}
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 14 }}>
        {OC_FILTER_OPTIONS.map(opt => {
          const isAll = opt.value === 'all';
          const active = filterStatus === opt.value;
          const count = isAll ? orders.length : (counts[opt.value] || 0);
          if (!isAll && count === 0) return null;
          const cfg = OC_STATUS_CFG[opt.value] || {};
          return (
            <button key={opt.value} onClick={() => setFilterStatus(opt.value)} style={{
              display: 'inline-flex', alignItems: 'center', gap: 5,
              padding: '5px 10px', borderRadius: 20, border: 'none', cursor: 'pointer',
              fontFamily: 'Kanit, sans-serif', fontSize: 12, fontWeight: active ? 600 : 400,
              background: active ? (isAll ? 'var(--ink)' : cfg.bg) : 'var(--bg-3)',
              color: active ? (isAll ? '#fff' : cfg.color) : 'var(--ink-3)',
              boxShadow: active ? '0 0 0 1.5px ' + (isAll ? 'var(--ink)' : (cfg.dot || cfg.color)) : 'none',
              transition: 'all 120ms',
            }}>
              {!isAll && cfg.dot && <span style={{ width: 6, height: 6, borderRadius: '50%', background: active ? cfg.dot : 'var(--ink-4)', flexShrink: 0 }}/>}
              {opt.label}
              <span style={{
                minWidth: 16, height: 16, borderRadius: 8, display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                background: active ? 'rgba(0,0,0,0.15)' : 'var(--bg-2)',
                color: active ? 'inherit' : 'var(--ink-3)',
                fontSize: 10, fontWeight: 600, padding: '0 4px',
              }}>{count}</span>
            </button>
          );
        })}
      </div>

      {loading ? (
        <div style={{ textAlign: 'center', padding: 60, color: 'var(--ink-3)', fontSize: 13 }}>กำลังโหลด...</div>
      ) : orders.length === 0 ? (
        <div style={{ textAlign: 'center', padding: 80, color: 'var(--ink-3)' }}>
          <Icon name="phone" size={32} color="var(--line-3)"/>
          <div style={{ fontSize: 14, marginTop: 12 }}>ยังไม่มี One Call Order</div>
          <div style={{ fontSize: 12, color: 'var(--ink-4)', marginTop: 4, marginBottom: 16 }}>กดปุ่มด้านบนเพื่อสร้าง Order แรก</div>
          <Button variant="primary" icon="plus" onClick={onNew}>New Order</Button>
        </div>
      ) : (
        <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 4, overflow: 'hidden' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ borderBottom: '1px solid var(--line)' }}>
                {['ORDER', 'COMPANY', 'STATUS', 'CREATED', ''].map(h => (
                  <th key={h} style={{ textAlign: 'left', padding: '10px 14px', fontSize: 10.5, color: 'var(--ink-3)', fontWeight: 600, letterSpacing: '0.06em', background: 'var(--bg-2)' }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {filtered.length === 0 ? (
                <tr><td colSpan={5} style={{ padding: '40px 14px', textAlign: 'center', fontSize: 13, color: 'var(--ink-3)' }}>
                  ไม่มี Order ใน status นี้
                </td></tr>
              ) : filtered.map((oc, i) => (
                <tr key={oc.id} style={{ borderBottom: i < filtered.length - 1 ? '1px solid var(--line-2)' : 'none' }}
                    onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-2)'}
                    onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                  <td style={{ padding: '12px 14px', fontSize: 12.5, fontFamily: 'IBM Plex Mono', color: 'var(--accent)' }}>{oc.orderNumber}</td>
                  <td style={{ padding: '12px 14px', fontSize: 13, fontWeight: 500 }}>{oc.companyData?.name || oc.companyId || '—'}</td>
                  <td style={{ padding: '12px 14px' }}><OcStatusChanger orderId={oc.id} status={oc.status} onChanged={handleStatusChange}/></td>
                  <td style={{ padding: '12px 14px', fontSize: 12, color: 'var(--ink-3)' }}>{fmtDate(oc.createdAt)}</td>
                  <td style={{ padding: '12px 14px', textAlign: 'right' }}>
                    <button onClick={() => onOpen(oc.id)} style={{
                      padding: '5px 12px', border: '1px solid var(--line)', borderRadius: 3,
                      background: 'transparent', color: 'var(--ink-2)', fontFamily: 'Kanit, sans-serif',
                      fontSize: 12, cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 4,
                    }}
                    onMouseEnter={e => { e.currentTarget.style.background = 'var(--bg-3)'; e.currentTarget.style.color = 'var(--ink)'; }}
                    onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--ink-2)'; }}>
                      ดูรายละเอียด <Icon name="chevron" size={9}/>
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
};

Object.assign(window, { OneCallOrderView, OcOrderListView });
