// SettingsScreen.jsx — AegisComply Settings + Auto-Quotation Config

const settingsStyles = {
  page: { padding: 24 },
  grid: { display: 'grid', gridTemplateColumns: '220px 1fr', gap: 20, alignItems: 'start' },
  sideNav: { background: 'white', border: '1px solid #E2E8F0', borderRadius: 8, overflow: 'hidden', boxShadow: '0 1px 3px rgba(0,0,0,0.05)' },
  navItem: { padding: '10px 16px', fontSize: 13, fontWeight: 500, color: '#475569', cursor: 'pointer', transition: 'all 150ms', borderLeft: '3px solid transparent', display: 'flex', alignItems: 'center', gap: 8 },
  navItemActive: { background: '#F0FDFA', color: '#0D9488', borderLeft: '3px solid #0D9488', fontWeight: 600 },
  navSection: { fontSize: 10, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#94A3B8', padding: '12px 16px 4px' },
  card: { background: 'white', border: '1px solid #E2E8F0', borderRadius: 8, padding: '20px 24px', boxShadow: '0 1px 3px rgba(0,0,0,0.05)', marginBottom: 16 },
  cardTitle: { fontFamily: "'Helvetica',sans-serif", fontSize: 15, fontWeight: 700, color: '#0F172A', marginBottom: 4 },
  cardSub: { fontSize: 12, color: '#64748B', marginBottom: 18, lineHeight: 1.5 },
  row: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16, gap: 16 },
  rowLabel: { fontSize: 13, fontWeight: 500, color: '#334155' },
  rowSub: { fontSize: 11, color: '#94A3B8', marginTop: 2 },
  toggle: { width: 44, height: 24, borderRadius: 12, cursor: 'pointer', position: 'relative', transition: 'background 200ms', flexShrink: 0, display: 'flex', alignItems: 'center', padding: '0 3px' },
  toggleKnob: { width: 18, height: 18, borderRadius: '50%', background: 'white', boxShadow: '0 1px 3px rgba(0,0,0,0.15)', transition: 'transform 200ms', flexShrink: 0 },
  fieldLabel: { fontSize: 12, fontWeight: 600, color: '#334155', display: 'block', marginBottom: 5 },
  fieldInput: { width: '100%', height: 36, border: '1px solid #CBD5E1', borderRadius: 6, padding: '0 12px', fontFamily: "'DM Sans',sans-serif", fontSize: 13, color: '#0F172A', outline: 'none', background: 'white' },
  saveBtn: { height: 34, padding: '0 18px', border: 'none', borderRadius: 6, background: '#0D9488', fontSize: 13, fontWeight: 600, color: 'white', cursor: 'pointer', fontFamily: "'DM Sans',sans-serif" },
  fieldGroup: { marginBottom: 14 },
  infoBox: { background: '#F0FDFA', border: '1px solid #99F6E4', borderRadius: 6, padding: '10px 14px', fontSize: 12, color: '#0F766E', marginBottom: 16, lineHeight: 1.6 },
  warningBox: { background: '#FFFBEB', border: '1px solid #FDE68A', borderRadius: 6, padding: '10px 14px', fontSize: 12, color: '#92400E', marginBottom: 16, lineHeight: 1.6 },
  grid2: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 },
  divider: { height: 1, background: '#F1F5F9', margin: '16px 0' },
  savedBadge: { display: 'inline-flex', alignItems: 'center', gap: 5, padding: '4px 12px', borderRadius: 5, background: '#F0FDF4', color: '#16A34A', fontSize: 12, fontWeight: 600, marginLeft: 12 },
};

const navSections = [
  { section: 'General', items: [{ id: 'profile', label: 'Profile & Company', icon: '👤' }, { id: 'users', label: 'User Management', icon: '👥' }] },
  { section: 'Automation', items: [{ id: 'quotation', label: 'Auto-Quotation', icon: '📧' }, { id: 'vendors', label: 'Labs & Suppliers', icon: '🏭' }, { id: 'notifications', label: 'Notifications', icon: '🔔' }] },
  { section: 'Modules', items: [{ id: 'calibration', label: 'Calibration Config', icon: '⚙️' }, { id: 'ppe', label: 'PPE Config', icon: '🦺' }] },
  { section: 'Account', items: [{ id: 'billing', label: 'Billing & Plan', icon: '💳' }, { id: 'security', label: 'Security', icon: '🔒' }] },
];

function Toggle({ on, onToggle }) {
  return (
    <div style={{ ...settingsStyles.toggle, background: on ? '#0D9488' : '#CBD5E1' }} onClick={onToggle}>
      <div style={{ ...settingsStyles.toggleKnob, transform: on ? 'translateX(20px)' : 'translateX(0)' }}/>
    </div>
  );
}

function AutoQuotationSettings({ user }) {
  const [saved, setSaved]       = React.useState(false);
  const [saving, setSaving]     = React.useState(false);
  const [loading, setLoading]   = React.useState(true);
  const [error, setError]       = React.useState('');
  const [settings, setSettings] = React.useState({
    cal_auto_quote: true,
    cal_days_before: 14,
    cal_provider_email: '',
    cal_dev_cc: true,
    dev_email: 'developer@aegiscomply.my',
    ppe_auto_quote: true,
    ppe_trigger: 'minimum',
    ppe_supplier_email: '',
    ppe_dev_cc: true,
    ppe_quote_qty: 'triple',
  });
  const set = (k, v) => { setSettings(s => ({ ...s, [k]: v })); setSaved(false); };

  React.useEffect(() => {
    if (!user) return;
    (async () => {
      try {
        const sb = window.supabaseClient;
        const { data, error: qErr } = await sb.from('account_settings').select('*').eq('user_id', user.id).maybeSingle();
        if (qErr) throw qErr;
        if (data) setSettings(s => ({ ...s, ...data }));
      } catch (err) {
        console.error('[Settings] load error:', err);
        setError(err.message);
      } finally {
        setLoading(false);
      }
    })();
  }, [user]);

  const handleSave = async () => {
    setSaving(true); setError('');
    try {
      const sb = window.supabaseClient;
      const payload = {
        user_id: user.id,
        cal_auto_quote:     settings.cal_auto_quote,
        cal_days_before:    Number(settings.cal_days_before) || 14,
        cal_provider_email: settings.cal_provider_email || null,
        cal_dev_cc:         settings.cal_dev_cc,
        ppe_auto_quote:     settings.ppe_auto_quote,
        ppe_trigger:        settings.ppe_trigger,
        ppe_supplier_email: settings.ppe_supplier_email || null,
        ppe_dev_cc:         settings.ppe_dev_cc,
        ppe_quote_qty:      settings.ppe_quote_qty,
        dev_email:          settings.dev_email || null,
      };
      const { error: upErr } = await sb.from('account_settings').upsert(payload, { onConflict: 'user_id' });
      if (upErr) throw upErr;
      setSaved(true);
      setTimeout(() => setSaved(false), 3000);
    } catch (err) {
      console.error('[Settings] save error:', err);
      setError(err.message || 'Save failed.');
    } finally {
      setSaving(false);
    }
  };

  if (loading) return <div style={settingsStyles.card}>Loading…</div>;

  return (
    <div>
      {/* Calibration Auto-Quotation */}
      <div style={settingsStyles.card}>
        <div style={settingsStyles.cardTitle}>Calibration Auto-Quotation</div>
        <div style={settingsStyles.cardSub}>
          When an equipment calibration is approaching its due date, AegisComply will automatically generate and send a quotation request to your preferred service provider.
        </div>

        {error && <div style={{ background: '#FFF5F5', border: '1px solid #FECACA', borderRadius: 6, padding: '8px 12px', fontSize: 12, color: '#DC2626', marginBottom: 12 }}>{error}</div>}

        <div style={settingsStyles.row}>
          <div>
            <div style={settingsStyles.rowLabel}>Enable auto-quotation for calibration</div>
            <div style={settingsStyles.rowSub}>Automatically email the service provider when due date is approaching</div>
          </div>
          <Toggle on={settings.cal_auto_quote} onToggle={() => set('cal_auto_quote', !settings.cal_auto_quote)}/>
        </div>

        {settings.cal_auto_quote && (
          <>
            <div style={settingsStyles.infoBox}>
              <strong>How it works:</strong> {settings.cal_days_before} days before calibration due date, the system sends a quotation request email to your configured service provider. You will receive a CC copy.
            </div>
            <div style={settingsStyles.grid2}>
              <div style={settingsStyles.fieldGroup}>
                <label style={settingsStyles.fieldLabel}>Days before due date to trigger</label>
                <select style={settingsStyles.fieldInput} value={settings.cal_days_before} onChange={e => set('cal_days_before', parseInt(e.target.value))}>
                  {[7,10,14,21,30].map(d => <option key={d} value={d}>{d} days before due date</option>)}
                </select>
              </div>
              <div style={settingsStyles.fieldGroup}>
                <label style={settingsStyles.fieldLabel}>Quotation sent to (service provider)</label>
                <input style={settingsStyles.fieldInput} type="email" placeholder="lab@sirim.my" value={settings.cal_provider_email || ''} onChange={e => set('cal_provider_email', e.target.value)}/>
              </div>
            </div>
            <div style={settingsStyles.divider}/>
            <div style={settingsStyles.row}>
              <div>
                <div style={settingsStyles.rowLabel}>CC developer / system admin</div>
                <div style={settingsStyles.rowSub}>Send a copy to your system developer for every auto-quotation</div>
              </div>
              <Toggle on={settings.cal_dev_cc} onToggle={() => set('cal_dev_cc', !settings.cal_dev_cc)}/>
            </div>
            {settings.cal_dev_cc && (
              <div style={settingsStyles.fieldGroup}>
                <label style={settingsStyles.fieldLabel}>Developer / Admin email (CC)</label>
                <input style={settingsStyles.fieldInput} type="email" value={settings.dev_email || ''} onChange={e => set('dev_email', e.target.value)}/>
              </div>
            )}
          </>
        )}
      </div>

      {/* PPE Auto-Quotation */}
      <div style={settingsStyles.card}>
        <div style={settingsStyles.cardTitle}>PPE Stock Auto-Quotation</div>
        <div style={settingsStyles.cardSub}>
          When PPE stock reaches the configured threshold, AegisComply automatically sends a quotation request to your supplier and notifies your team.
        </div>

        <div style={settingsStyles.row}>
          <div>
            <div style={settingsStyles.rowLabel}>Enable auto-quotation for PPE</div>
            <div style={settingsStyles.rowSub}>Automatically email supplier when stock falls below threshold</div>
          </div>
          <Toggle on={settings.ppe_auto_quote} onToggle={() => set('ppe_auto_quote', !settings.ppe_auto_quote)}/>
        </div>

        {settings.ppe_auto_quote && (
          <>
            <div style={settingsStyles.infoBox}>
              <strong>How it works:</strong> When any PPE item stock drops to or below the minimum threshold, a quotation request is immediately sent to your configured supplier email.
            </div>
            <div style={settingsStyles.grid2}>
              <div style={settingsStyles.fieldGroup}>
                <label style={settingsStyles.fieldLabel}>Trigger at stock level</label>
                <select style={settingsStyles.fieldInput} value={settings.ppe_trigger} onChange={e => set('ppe_trigger', e.target.value)}>
                  <option value="minimum">At minimum threshold (exact)</option>
                  <option value="double">At 2× minimum threshold (early)</option>
                  <option value="critical">Only at critical (below 50% of minimum)</option>
                </select>
              </div>
              <div style={settingsStyles.fieldGroup}>
                <label style={settingsStyles.fieldLabel}>Suggested order quantity</label>
                <select style={settingsStyles.fieldInput} value={settings.ppe_quote_qty} onChange={e => set('ppe_quote_qty', e.target.value)}>
                  <option value="minimum">Fill to minimum (exact gap)</option>
                  <option value="double">2× minimum stock level</option>
                  <option value="triple">3× minimum stock level (recommended)</option>
                </select>
              </div>
            </div>
            <div style={settingsStyles.fieldGroup}>
              <label style={settingsStyles.fieldLabel}>Supplier email (quotation sent to)</label>
              <input style={settingsStyles.fieldInput} type="email" placeholder="supplier@company.com" value={settings.ppe_supplier_email || ''} onChange={e => set('ppe_supplier_email', e.target.value)}/>
            </div>
            <div style={settingsStyles.row}>
              <div>
                <div style={settingsStyles.rowLabel}>CC developer / system admin</div>
                <div style={settingsStyles.rowSub}>Send a copy to your system developer for every auto-quotation</div>
              </div>
              <Toggle on={settings.ppe_dev_cc} onToggle={() => set('ppe_dev_cc', !settings.ppe_dev_cc)}/>
            </div>
          </>
        )}
      </div>

      <div style={{ display: 'flex', alignItems: 'center' }}>
        <button
          style={{ ...settingsStyles.saveBtn, ...(saving ? { background: '#CBD5E1', cursor: 'not-allowed' } : {}) }}
          onClick={handleSave}
          disabled={saving}
        >
          {saving ? 'Saving…' : 'Save Settings'}
        </button>
        {saved && <span style={settingsStyles.savedBadge}><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>Saved</span>}
      </div>
    </div>
  );
}

function ProfileSettings({ user }) {
  const [form, setForm] = React.useState({
    name:     user?.name || '',
    role:     user?.role || 'Safety Officer',
    email:    user?.email || '',
    phone:    user?.phone || '',
    whatsapp: user?.whatsapp || '',
    company:  user?.company || '',
  });
  const [saving, setSaving] = React.useState(false);
  const [saved, setSaved]   = React.useState(false);
  const [error, setError]   = React.useState('');
  const set = (k, v) => { setForm(f => ({ ...f, [k]: v })); setSaved(false); };

  const handleSave = async () => {
    setSaving(true); setError('');
    try {
      const sb = window.supabaseClient;
      const { error: upErr } = await sb.from('users').update({
        name:     form.name,
        role:     form.role,
        phone:    form.phone || null,
        whatsapp: form.whatsapp || null,
        company:  form.company,
      }).eq('id', user.id);
      if (upErr) throw upErr;
      setSaved(true);
      setTimeout(() => setSaved(false), 3000);
    } catch (err) {
      console.error('[Profile] save error:', err);
      setError(err.message || 'Save failed.');
    } finally {
      setSaving(false);
    }
  };

  return (
    <div style={settingsStyles.card}>
      <div style={settingsStyles.cardTitle}>Profile & Company</div>
      <div style={settingsStyles.cardSub}>Update your account information and company details.</div>
      {error && <div style={{ background: '#FFF5F5', border: '1px solid #FECACA', borderRadius: 6, padding: '8px 12px', fontSize: 12, color: '#DC2626', marginBottom: 12 }}>{error}</div>}
      <div style={settingsStyles.grid2}>
        <div style={settingsStyles.fieldGroup}>
          <label style={settingsStyles.fieldLabel}>Full Name</label>
          <input style={settingsStyles.fieldInput} value={form.name} onChange={e => set('name', e.target.value)}/>
        </div>
        <div style={settingsStyles.fieldGroup}>
          <label style={settingsStyles.fieldLabel}>Role</label>
          <input style={settingsStyles.fieldInput} value={form.role} onChange={e => set('role', e.target.value)}/>
        </div>
        <div style={settingsStyles.fieldGroup}>
          <label style={settingsStyles.fieldLabel}>Email <span style={{ fontWeight: 400, color: '#94A3B8' }}>(read-only)</span></label>
          <input style={{ ...settingsStyles.fieldInput, background: '#F8FAFC', color: '#64748B' }} type="email" value={form.email} disabled/>
        </div>
        <div style={settingsStyles.fieldGroup}>
          <label style={settingsStyles.fieldLabel}>Phone</label>
          <input style={settingsStyles.fieldInput} placeholder="+60 12-345 6789" value={form.phone} onChange={e => set('phone', e.target.value)}/>
        </div>
        <div style={settingsStyles.fieldGroup}>
          <label style={settingsStyles.fieldLabel}>WhatsApp</label>
          <input style={settingsStyles.fieldInput} placeholder="+60 12-345 6789" value={form.whatsapp} onChange={e => set('whatsapp', e.target.value)}/>
        </div>
        <div style={settingsStyles.fieldGroup}>
          <label style={settingsStyles.fieldLabel}>Company Name</label>
          <input style={settingsStyles.fieldInput} value={form.company} onChange={e => set('company', e.target.value)}/>
        </div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center' }}>
        <button
          style={{ ...settingsStyles.saveBtn, ...(saving ? { background: '#CBD5E1', cursor: 'not-allowed' } : {}) }}
          onClick={handleSave}
          disabled={saving}
        >
          {saving ? 'Saving…' : 'Save Profile'}
        </button>
        {saved && <span style={settingsStyles.savedBadge}><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>Saved</span>}
      </div>
    </div>
  );
}

// ── Vendors (Labs & Suppliers) Management ─────────────────────────────────
function VendorsManagement({ user }) {
  const [type, setType]         = React.useState('cal_lab'); // 'cal_lab' | 'ppe_supplier'
  const [vendors, setVendors]   = React.useState([]);
  const [loading, setLoading]   = React.useState(false);
  const [error, setError]       = React.useState('');
  const [editing, setEditing]   = React.useState(null); // null | 'new' | vendor

  const fetchVendors = React.useCallback(async () => {
    setLoading(true); setError('');
    try {
      const sb = window.supabaseClient;
      const { data, error: qErr } = await sb.from('vendors').select('*').order('is_default', { ascending: false }).order('name');
      if (qErr) throw qErr;
      setVendors(data || []);
    } catch (err) {
      console.error('[Vendors] fetch error:', err);
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }, []);

  React.useEffect(() => { fetchVendors(); }, [fetchVendors]);

  // Realtime
  React.useEffect(() => {
    if (!user) return;
    const sb = window.supabaseClient;
    if (!sb) return;
    const ch = sb.channel(`vendors-${user.id}`)
      .on('postgres_changes', { event: '*', schema: 'public', table: 'vendors', filter: `user_id=eq.${user.id}` }, () => fetchVendors())
      .subscribe();
    return () => { sb.removeChannel(ch); };
  }, [user, fetchVendors]);

  const handleDelete = async (vendorId) => {
    if (!confirm('Delete this vendor?')) return;
    try {
      const sb = window.supabaseClient;
      const { error: delErr } = await sb.from('vendors').delete().eq('id', vendorId);
      if (delErr) throw delErr;
    } catch (err) {
      alert('Delete failed: ' + err.message);
    }
  };

  const handleSetDefault = async (vendorId, vendorType) => {
    try {
      const sb = window.supabaseClient;
      // Unset all defaults of this type first
      await sb.from('vendors').update({ is_default: false }).eq('type', vendorType);
      // Set this one as default
      const { error: upErr } = await sb.from('vendors').update({ is_default: true }).eq('id', vendorId);
      if (upErr) throw upErr;
    } catch (err) {
      alert('Update failed: ' + err.message);
    }
  };

  const filtered = vendors.filter(v => v.type === type);

  return (
    <div>
      <div style={settingsStyles.card}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
          <div>
            <div style={settingsStyles.cardTitle}>Saved Labs & Suppliers</div>
            <div style={{ ...settingsStyles.cardSub, marginBottom: 0 }}>Pre-saved contacts used in Booking + Reorder modals and scheduled reminders.</div>
          </div>
          <button
            style={settingsStyles.saveBtn}
            onClick={() => setEditing('new')}
          >
            + Add {type === 'cal_lab' ? 'Lab' : 'Supplier'}
          </button>
        </div>

        {/* Type tabs */}
        <div style={{ display: 'flex', gap: 4, marginBottom: 14, background: '#F1F5F9', padding: 3, borderRadius: 6, width: 'fit-content' }}>
          {[
            { id: 'cal_lab', label: '🔬 Calibration Labs' },
            { id: 'ppe_supplier', label: '🦺 PPE Suppliers' },
          ].map(t => (
            <button
              key={t.id}
              onClick={() => setType(t.id)}
              style={{
                padding: '6px 14px',
                borderRadius: 5,
                fontSize: 12,
                fontWeight: 600,
                cursor: 'pointer',
                border: 'none',
                background: type === t.id ? 'white' : 'transparent',
                color: type === t.id ? '#0F172A' : '#64748B',
                fontFamily: "'DM Sans',sans-serif",
                boxShadow: type === t.id ? '0 1px 3px rgba(0,0,0,0.06)' : 'none',
              }}
            >
              {t.label}
            </button>
          ))}
        </div>

        {error && <div style={{ background: '#FFF5F5', border: '1px solid #FECACA', borderRadius: 6, padding: '8px 12px', fontSize: 12, color: '#DC2626', marginBottom: 12 }}>{error}</div>}

        {loading && filtered.length === 0 ? (
          <div style={{ padding: 30, textAlign: 'center', color: '#94A3B8', fontSize: 13 }}>Loading…</div>
        ) : filtered.length === 0 ? (
          <div style={{ padding: 30, textAlign: 'center', color: '#94A3B8', fontSize: 13, border: '1px dashed #E2E8F0', borderRadius: 8 }}>
            No {type === 'cal_lab' ? 'calibration labs' : 'PPE suppliers'} saved yet.<br/>
            <span style={{ fontSize: 11 }}>Click "Add" above to save one for quick reuse.</span>
          </div>
        ) : (
          <div style={{ border: '1px solid #E2E8F0', borderRadius: 8, overflow: 'hidden' }}>
            {filtered.map((v, i) => (
              <div key={v.id} style={{ display: 'grid', gridTemplateColumns: '2fr 1.5fr 1fr 110px', gap: 10, padding: '12px 14px', borderBottom: i === filtered.length - 1 ? 'none' : '1px solid #F1F5F9', alignItems: 'center', background: v.is_default ? '#F0FDFA' : 'white' }}>
                <div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    <span style={{ fontSize: 13, fontWeight: 600, color: '#0F172A' }}>{v.name}</span>
                    {v.is_default && <span style={{ fontSize: 9, fontWeight: 700, background: '#0D9488', color: 'white', padding: '1px 7px', borderRadius: 3, letterSpacing: '0.04em' }}>DEFAULT</span>}
                  </div>
                  {v.specialty && <div style={{ fontSize: 11, color: '#94A3B8', marginTop: 2 }}>{v.specialty}</div>}
                </div>
                <div style={{ fontSize: 12, color: '#475569', wordBreak: 'break-all' }}>{v.email}</div>
                <div style={{ fontSize: 11, color: '#94A3B8' }}>{v.phone || v.whatsapp || '—'}</div>
                <div style={{ display: 'flex', gap: 4, justifyContent: 'flex-end' }}>
                  {!v.is_default && (
                    <button onClick={() => handleSetDefault(v.id, v.type)} style={{ height: 26, padding: '0 8px', borderRadius: 4, border: '1px solid #CBD5E1', background: 'white', fontSize: 11, color: '#475569', cursor: 'pointer', fontFamily: "'DM Sans',sans-serif" }} title="Set as default">
                      Set default
                    </button>
                  )}
                  <button onClick={() => setEditing(v)} style={{ height: 26, padding: '0 8px', borderRadius: 4, border: '1px solid #CBD5E1', background: 'white', fontSize: 11, color: '#475569', cursor: 'pointer', fontFamily: "'DM Sans',sans-serif" }}>
                    Edit
                  </button>
                  <button onClick={() => handleDelete(v.id)} style={{ height: 26, padding: '0 8px', borderRadius: 4, border: '1px solid #FECACA', background: 'white', fontSize: 11, color: '#DC2626', cursor: 'pointer', fontFamily: "'DM Sans',sans-serif" }}>
                    ✕
                  </button>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {editing && (
        <VendorFormModal
          initial={editing === 'new' ? { type } : editing}
          user={user}
          onClose={() => setEditing(null)}
          onSaved={() => { setEditing(null); fetchVendors(); }}
        />
      )}
    </div>
  );
}

function VendorFormModal({ initial, user, onClose, onSaved }) {
  const empty = { type: 'cal_lab', name: '', email: '', phone: '', whatsapp: '', specialty: '', notes: '', is_default: false };
  const [form, setForm] = React.useState({ ...empty, ...initial });
  const [saving, setSaving] = React.useState(false);
  const [error, setError]   = React.useState('');
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const isEdit = !!initial?.id;
  const valid = form.name.trim() && form.email.trim() && /\S+@\S+\.\S+/.test(form.email);

  const handleSubmit = async () => {
    setError('');
    if (!valid) { setError('Name and a valid email are required.'); return; }
    setSaving(true);
    try {
      const sb = window.supabaseClient;
      const payload = {
        user_id:    user.id,
        type:       form.type,
        name:       form.name.trim(),
        email:      form.email.trim().toLowerCase(),
        phone:      form.phone || null,
        whatsapp:   form.whatsapp || null,
        specialty:  form.specialty || null,
        notes:      form.notes || null,
        is_default: form.is_default,
      };
      if (form.is_default) {
        // Unset other defaults of this type first
        await sb.from('vendors').update({ is_default: false }).eq('type', form.type);
      }
      if (isEdit) {
        const { error: upErr } = await sb.from('vendors').update(payload).eq('id', initial.id);
        if (upErr) throw upErr;
      } else {
        const { error: insErr } = await sb.from('vendors').insert(payload);
        if (insErr) throw insErr;
      }
      onSaved();
    } catch (err) {
      console.error('[Vendor] save error:', err);
      setError(err.message);
    } finally {
      setSaving(false);
    }
  };

  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.55)', zIndex: 9000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }} onClick={saving ? undefined : onClose}>
      <div style={{ background: 'white', borderRadius: 12, width: '100%', maxWidth: 520, boxShadow: '0 16px 48px rgba(0,0,0,0.2)', maxHeight: '90vh', overflowY: 'auto' }} onClick={e => e.stopPropagation()}>
        <div style={{ padding: '18px 24px', borderBottom: '1px solid #E2E8F0' }}>
          <div style={{ fontFamily: "'Helvetica',Arial,sans-serif", fontSize: 16, fontWeight: 700, color: '#0F172A' }}>
            {isEdit ? 'Edit' : 'Add'} {form.type === 'cal_lab' ? 'Calibration Lab' : 'PPE Supplier'}
          </div>
        </div>
        <div style={{ padding: '20px 24px' }}>
          {error && <div style={{ background: '#FFF5F5', border: '1px solid #FECACA', borderRadius: 6, padding: '8px 12px', fontSize: 12, color: '#DC2626', marginBottom: 12 }}>{error}</div>}

          {!isEdit && (
            <div style={settingsStyles.fieldGroup}>
              <label style={settingsStyles.fieldLabel}>Type</label>
              <select style={settingsStyles.fieldInput} value={form.type} onChange={e => set('type', e.target.value)}>
                <option value="cal_lab">Calibration Lab</option>
                <option value="ppe_supplier">PPE Supplier</option>
              </select>
            </div>
          )}

          <div style={settingsStyles.fieldGroup}>
            <label style={settingsStyles.fieldLabel}>Name *</label>
            <input style={settingsStyles.fieldInput} placeholder="e.g. SIRIM Bhd" value={form.name} onChange={e => set('name', e.target.value)}/>
          </div>

          <div style={settingsStyles.fieldGroup}>
            <label style={settingsStyles.fieldLabel}>Email *</label>
            <input style={settingsStyles.fieldInput} type="email" placeholder="contact@example.com" value={form.email} onChange={e => set('email', e.target.value)}/>
          </div>

          <div style={settingsStyles.grid2}>
            <div style={settingsStyles.fieldGroup}>
              <label style={settingsStyles.fieldLabel}>Phone</label>
              <input style={settingsStyles.fieldInput} placeholder="+60 1x-xxx xxxx" value={form.phone} onChange={e => set('phone', e.target.value)}/>
            </div>
            <div style={settingsStyles.fieldGroup}>
              <label style={settingsStyles.fieldLabel}>WhatsApp</label>
              <input style={settingsStyles.fieldInput} placeholder="+60 1x-xxx xxxx" value={form.whatsapp} onChange={e => set('whatsapp', e.target.value)}/>
            </div>
          </div>

          <div style={settingsStyles.fieldGroup}>
            <label style={settingsStyles.fieldLabel}>Specialty / Notes</label>
            <input style={settingsStyles.fieldInput} placeholder={form.type === 'cal_lab' ? 'e.g. Pressure & Gas instruments' : 'e.g. Gloves, hearing protection'} value={form.specialty} onChange={e => set('specialty', e.target.value)}/>
          </div>

          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <input type="checkbox" id="vendor-default" checked={form.is_default} onChange={e => set('is_default', e.target.checked)}/>
            <label htmlFor="vendor-default" style={{ fontSize: 13, color: '#334155', cursor: 'pointer' }}>Make this the default for {form.type === 'cal_lab' ? 'calibration bookings' : 'PPE reorders'}</label>
          </div>
        </div>
        <div style={{ padding: '14px 24px', borderTop: '1px solid #E2E8F0', display: 'flex', justifyContent: 'flex-end', gap: 8, background: '#F8FAFC' }}>
          <button onClick={onClose} disabled={saving} style={{ height: 34, padding: '0 14px', border: '1px solid #CBD5E1', borderRadius: 6, background: 'white', fontSize: 13, color: '#64748B', cursor: 'pointer', fontFamily: "'DM Sans',sans-serif" }}>
            Cancel
          </button>
          <button
            onClick={handleSubmit}
            disabled={!valid || saving}
            style={{ height: 34, padding: '0 16px', border: 'none', borderRadius: 6, background: (!valid || saving) ? '#CBD5E1' : '#0D9488', fontSize: 13, fontWeight: 700, color: 'white', cursor: (!valid || saving) ? 'not-allowed' : 'pointer', fontFamily: "'DM Sans',sans-serif" }}
          >
            {saving ? 'Saving…' : isEdit ? 'Save Changes' : 'Add Vendor'}
          </button>
        </div>
      </div>
    </div>
  );
}

function PlaceholderSection({ title }) {
  return (
    <div style={settingsStyles.card}>
      <div style={settingsStyles.cardTitle}>{title}</div>
      <div style={{ color: '#94A3B8', fontSize: 13, padding: '20px 0', textAlign: 'center' }}>This settings section is part of the UI kit prototype — not yet fully built.</div>
    </div>
  );
}

function SettingsScreen({ user }) {
  const [active, setActive] = React.useState('quotation');

  const renderContent = () => {
    switch (active) {
      case 'profile':       return <ProfileSettings user={user}/>;
      case 'quotation':     return <AutoQuotationSettings user={user}/>;
      case 'vendors':       return <VendorsManagement user={user}/>;
      default:              return <PlaceholderSection title={navSections.flatMap(s => s.items).find(i => i.id === active)?.label || 'Settings'}/>;
    }
  };

  return (
    <div style={settingsStyles.page}>
      <div style={settingsStyles.grid}>
        <div style={settingsStyles.sideNav}>
          {navSections.map((s, i) => (
            <React.Fragment key={i}>
              <div style={settingsStyles.navSection}>{s.section}</div>
              {s.items.map(item => (
                <div key={item.id} style={{ ...settingsStyles.navItem, ...(active === item.id ? settingsStyles.navItemActive : {}) }} onClick={() => setActive(item.id)}>
                  <span style={{ fontSize: 14 }}>{item.icon}</span>{item.label}
                </div>
              ))}
            </React.Fragment>
          ))}
        </div>
        <div>{renderContent()}</div>
      </div>
    </div>
  );
}

Object.assign(window, { SettingsScreen });
