// MaxAMove CRM — Settings tab
// =============================
// Seven sub-tabs:
//   1. Company          (company info + USDOT/MC + service area + tax)
//   2. Pricing          (crew-size-based rates + surcharges + travel/min rules)
//   3. Capacity         (avg weight per mover + truck defaults + booking rules)
//   4. Documents        (upload & categorize form templates)
//   5. My Profile       (name/phone/password/sign-out)
//   6. Team             (owner-only — list users, change roles, deactivate)
//   7. Crew Members     (owner/staff — list, add, edit crew)

const { useState, useEffect, useRef } = React;

// =============================================================================
// Shared UI primitives (local to Settings — not exported globally)
// =============================================================================

const S_styles = {
  page: { display: 'flex', flexDirection: 'column', height: '100%' },
  header: { marginBottom: 14 },
  h1: { fontSize: 22, fontWeight: 900, fontFamily: 'Poppins', marginBottom: 2 },
  subtitle: { color: 'var(--muted)', fontSize: 14 },
  tabsRow: { display: 'flex', gap: 6, borderBottom: '1px solid var(--border)', marginBottom: 20, overflowX: 'auto', paddingBottom: 2 },
  tabBtn: { padding: '9px 14px', background: 'transparent', border: 'none', color: 'var(--muted)', fontSize: 13, fontWeight: 600, borderBottom: '2px solid transparent', cursor: 'pointer', whiteSpace: 'nowrap', fontFamily: 'inherit', marginBottom: -1 },
  tabBtnActive: { color: 'var(--accent-dark)', borderBottomColor: 'var(--accent)', fontWeight: 700 },
  card: { background: 'var(--card)', borderRadius: 14, border: '1px solid var(--border)', padding: 22, marginBottom: 18 },
  cardTitle: { fontWeight: 800, fontSize: 15, fontFamily: 'Poppins', marginBottom: 4 },
  cardSubtitle: { color: 'var(--muted)', fontSize: 12, marginBottom: 16 },
  field: { marginBottom: 14 },
  label: { display: 'block', fontSize: 11, fontWeight: 700, letterSpacing: '0.07em', textTransform: 'uppercase', color: 'var(--muted)', marginBottom: 6 },
  input: { width: '100%', boxSizing: 'border-box', padding: '10px 12px', borderRadius: 9, border: '1.5px solid var(--border)', background: 'var(--input-bg)', color: 'var(--text)', fontSize: 14, fontFamily: 'inherit', outline: 'none' },
  textarea: { width: '100%', boxSizing: 'border-box', padding: '10px 12px', borderRadius: 9, border: '1.5px solid var(--border)', background: 'var(--input-bg)', color: 'var(--text)', fontSize: 14, fontFamily: 'inherit', outline: 'none', resize: 'vertical', minHeight: 70 },
  row2: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 },
  row3: { display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 14 },
  btnPrimary: { padding: '10px 18px', background: 'linear-gradient(135deg,#14C6BF,#3DCC7E)', color: '#fff', border: 'none', borderRadius: 9, fontSize: 13, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit' },
  btnSecondary: { padding: '9px 14px', background: 'var(--bg)', color: 'var(--text)', border: '1.5px solid var(--border)', borderRadius: 9, fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' },
  btnDanger: { padding: '9px 14px', background: '#fef2f2', color: '#b91c1c', border: '1.5px solid #fecaca', borderRadius: 9, fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' },
  toastOk: { background: '#f0fdf4', border: '1px solid #bbf7d0', color: '#166534', padding: '10px 14px', borderRadius: 9, fontSize: 13, fontWeight: 600, marginBottom: 14 },
  toastErr: { background: '#fef2f2', border: '1px solid #fecaca', color: '#b91c1c', padding: '10px 14px', borderRadius: 9, fontSize: 13, fontWeight: 600, marginBottom: 14 },
  toastInfo: { background: '#eff6ff', border: '1px solid #bfdbfe', color: '#1e40af', padding: '10px 14px', borderRadius: 9, fontSize: 13, fontWeight: 600, marginBottom: 14 },
  hint: { fontSize: 11, color: 'var(--muted)', marginTop: 4, lineHeight: 1.4 },
  pill: { display: 'inline-block', padding: '2px 8px', borderRadius: 10, fontSize: 10, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase' },
};

function Toast({ kind = 'ok', children }) {
  const s = kind === 'err' ? S_styles.toastErr : kind === 'info' ? S_styles.toastInfo : S_styles.toastOk;
  if (!children) return null;
  return <div style={s}>{children}</div>;
}

function SField({ label, hint, children }) {
  return (
    <div style={S_styles.field}>
      {label && <label style={S_styles.label}>{label}</label>}
      {children}
      {hint && <div style={S_styles.hint}>{hint}</div>}
    </div>
  );
}

function SInput(props) {
  return <input style={{ ...S_styles.input, ...(props.style || {}) }} {...props} />;
}

function STextarea(props) {
  return <textarea style={{ ...S_styles.textarea, ...(props.style || {}) }} {...props} />;
}

function SSelect({ value, onChange, children, style = {} }) {
  return (
    <select
      value={value}
      onChange={e => onChange(e.target.value)}
      style={{ ...S_styles.input, appearance: 'none',
        backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8' viewBox='0 0 12 8'%3E%3Cpath d='M1 1l5 5 5-5' stroke='%23999' stroke-width='1.5' fill='none' stroke-linecap='round'/%3E%3C/svg%3E")`,
        backgroundRepeat: 'no-repeat', backgroundPosition: 'right 12px center', paddingRight: 36, cursor: 'pointer',
        ...style }}
    >
      {children}
    </select>
  );
}

function SCheck({ checked, onChange, label }) {
  return (
    <label style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer', fontSize: 13, color: 'var(--text)' }}>
      <input type="checkbox" checked={!!checked} onChange={e => onChange(e.target.checked)}
        style={{ width: 16, height: 16, accentColor: '#14C6BF', cursor: 'pointer' }} />
      <span>{label}</span>
    </label>
  );
}

function SectionCard({ title, subtitle, children, action }) {
  return (
    <div style={S_styles.card}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 10 }}>
        <div style={{ flex: 1 }}>
          {title && <div style={S_styles.cardTitle}>{title}</div>}
          {subtitle && <div style={S_styles.cardSubtitle}>{subtitle}</div>}
        </div>
        {action}
      </div>
      {children}
    </div>
  );
}

// =============================================================================
// 1. COMPANY SECTION
// =============================================================================

function CompanySection() {
  const [form, setForm] = useState(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [ok, setOk] = useState('');
  const [err, setErr] = useState('');

  useEffect(() => {
    window.loadSettings().then(s => { setForm(s); setLoading(false); })
      .catch(e => { setErr(e.message); setLoading(false); });
  }, []);

  const u = (k, v) => setForm(f => ({ ...f, [k]: v }));

  async function save() {
    setSaving(true); setOk(''); setErr('');
    try {
      // Strip blanks/dupes from lead sources (case-insensitive de-dupe)
      const seen = new Set();
      const cleanSources = (form.leadSources || [])
        .map(s => (s || '').trim())
        .filter(s => {
          if (!s) return false;
          const key = s.toLowerCase();
          if (seen.has(key)) return false;
          seen.add(key);
          return true;
        });

      await window.saveSettings({
        companyName: form.companyName,
        taxRate: Number(form.taxRate) || 0,
        emailFrom: form.emailFrom,
        smsFromNumber: form.smsFromNumber,
        address: form.address,
        phone: form.phone,
        businessEmail: form.businessEmail,
        usdotNumber: form.usdotNumber,
        mcNumber: form.mcNumber,
        serviceArea: form.serviceArea,
        leadSources: cleanSources.length ? cleanSources : (window.DEFAULT_LEAD_SOURCES || []),
      });
      setOk('Company info saved.');
      setTimeout(() => setOk(''), 3000);
    } catch (e) {
      setErr(e.message || 'Failed to save.');
    } finally {
      setSaving(false);
    }
  }

  if (loading || !form) return <div style={{ color: 'var(--muted)' }}>Loading company info…</div>;

  return (
    <div>
      <Toast kind="ok">{ok}</Toast>
      <Toast kind="err">{err}</Toast>

      <SectionCard title="Company identity" subtitle="Shown on estimates, invoices, and Bills of Lading.">
        <div style={S_styles.row2}>
          <SField label="Company name">
            <SInput value={form.companyName} onChange={e => u('companyName', e.target.value)} placeholder="MaxAMove LLC" />
          </SField>
          <SField label="Service area" hint="E.g. 'Austin & Central Texas'">
            <SInput value={form.serviceArea} onChange={e => u('serviceArea', e.target.value)} placeholder="Austin metro" />
          </SField>
        </div>
        <SField label="Office address" hint="Full address including ZIP — appears on your documents.">
          <STextarea value={form.address} onChange={e => u('address', e.target.value)} placeholder="123 Main St, Austin, TX 78701" />
        </SField>
      </SectionCard>

      <SectionCard title="Contact info" subtitle="Where customers and vendors reach you.">
        <div style={S_styles.row2}>
          <SField label="Business phone">
            <SInput value={form.phone} onChange={e => u('phone', e.target.value)} placeholder="(555) 123-4567" />
          </SField>
          <SField label="Business email">
            <SInput value={form.businessEmail} onChange={e => u('businessEmail', e.target.value)} placeholder="ops@maxamove.com" />
          </SField>
        </div>
        <div style={S_styles.row2}>
          <SField label="Outbound email 'from'" hint="Used when the CRM sends estimates/invoices.">
            <SInput value={form.emailFrom} onChange={e => u('emailFrom', e.target.value)} placeholder="ops@maxamove.com" />
          </SField>
          <SField label="Outbound SMS number" hint="Used when the CRM sends SMS (future).">
            <SInput value={form.smsFromNumber} onChange={e => u('smsFromNumber', e.target.value)} placeholder="(555) 123-4567" />
          </SField>
        </div>
      </SectionCard>

      <SectionCard title="Licensing & compliance" subtitle="Required on BOLs and interstate paperwork.">
        <div style={S_styles.row2}>
          <SField label="USDOT number" hint="U.S. Department of Transportation number.">
            <SInput value={form.usdotNumber} onChange={e => u('usdotNumber', e.target.value)} placeholder="USDOT 1234567" />
          </SField>
          <SField label="MC number" hint="FMCSA Motor Carrier authority number (interstate only).">
            <SInput value={form.mcNumber} onChange={e => u('mcNumber', e.target.value)} placeholder="MC 123456" />
          </SField>
        </div>
      </SectionCard>

      <SectionCard title="Tax" subtitle="Default sales tax rate used on invoices.">
        <div style={{ maxWidth: 220 }}>
          <SField label="Sales tax rate (decimal)" hint='Example: 0.0825 means 8.25%.'>
            <SInput type="number" step="0.0001" value={form.taxRate} onChange={e => u('taxRate', e.target.value)} />
          </SField>
        </div>
      </SectionCard>

      <SectionCard title="Lead sources" subtitle="The dropdown shown when adding a new lead. Add channels you actually use; remove the ones you don't.">
        <LeadSourcesEditor
          value={form.leadSources || (window.DEFAULT_LEAD_SOURCES || [])}
          onChange={list => u('leadSources', list)}
        />
      </SectionCard>

      <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
        <button style={S_styles.btnPrimary} onClick={save} disabled={saving}>
          {saving ? 'Saving…' : 'Save company info'}
        </button>
      </div>
    </div>
  );
}

// Inline list editor: rows of [text input | remove], plus an "Add source" button
// at the bottom. Pure presentational — owner section owns the save lifecycle.
function LeadSourcesEditor({ value, onChange }) {
  const list = Array.isArray(value) ? value : [];
  const update = (i, v) => {
    const next = [...list];
    next[i] = v;
    onChange(next);
  };
  const remove = i => onChange(list.filter((_, idx) => idx !== i));
  const add = () => onChange([...list, '']);
  return (
    <div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {list.map((s, i) => (
          <div key={i} style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            <div style={{ flex: 1 }}>
              <SInput
                value={s}
                onChange={e => update(i, e.target.value)}
                placeholder="e.g. Thumbtack"
              />
            </div>
            <button
              type="button"
              onClick={() => remove(i)}
              title="Remove this source"
              style={{ padding: '7px 12px', borderRadius: 8, border: '1.5px solid #fecaca', background: '#fef2f2', color: '#b91c1c', fontWeight: 700, fontFamily: 'inherit', cursor: 'pointer', fontSize: 12 }}>
              Remove
            </button>
          </div>
        ))}
        {list.length === 0 && (
          <div style={{ color: 'var(--muted)', fontSize: 12, padding: '6px 0' }}>No sources yet — add one below.</div>
        )}
      </div>
      <button
        type="button"
        onClick={add}
        style={{ marginTop: 12, padding: '8px 14px', borderRadius: 8, border: '1.5px dashed var(--border)', background: 'transparent', color: 'var(--accent-dark)', fontWeight: 700, fontFamily: 'inherit', cursor: 'pointer', fontSize: 13 }}>
        + Add source
      </button>
      <div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 10 }}>
        Click <b>Save company info</b> below to apply changes. Existing leads keep their original source even if you remove it from the list.
      </div>
    </div>
  );
}

// =============================================================================
// 2. PRICING SECTION
// =============================================================================

function PricingSection() {
  const [form, setForm] = useState(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [ok, setOk] = useState('');
  const [err, setErr] = useState('');

  useEffect(() => {
    window.loadSettings().then(s => { setForm(s); setLoading(false); })
      .catch(e => { setErr(e.message); setLoading(false); });
  }, []);

  function updateTier(i, key, val) {
    setForm(f => {
      const tiers = [...f.pricingTiers];
      tiers[i] = { ...tiers[i], [key]: key === 'crewSize' ? Math.max(1, parseInt(val) || 1) : (parseFloat(val) || 0) };
      return { ...f, pricingTiers: tiers };
    });
  }

  function addTier() {
    setForm(f => {
      const maxSize = Math.max(0, ...f.pricingTiers.map(t => t.crewSize || 0));
      return { ...f, pricingTiers: [...f.pricingTiers, { crewSize: maxSize + 1, hourlyRate: 0 }] };
    });
  }

  function removeTier(i) {
    setForm(f => ({ ...f, pricingTiers: f.pricingTiers.filter((_, idx) => idx !== i) }));
  }

  // Labor-only tier helpers — same shape as pricingTiers but for labor-only jobs
  function updateLaborTier(i, key, val) {
    setForm(f => {
      const tiers = [...(f.laborOnlyTiers || [])];
      tiers[i] = { ...tiers[i], [key]: key === 'crewSize' ? Math.max(1, parseInt(val) || 1) : (parseFloat(val) || 0) };
      return { ...f, laborOnlyTiers: tiers };
    });
  }
  function addLaborTier() {
    setForm(f => {
      const tiers = f.laborOnlyTiers || [];
      const maxSize = Math.max(0, ...tiers.map(t => t.crewSize || 0));
      return { ...f, laborOnlyTiers: [...tiers, { crewSize: maxSize + 1, hourlyRate: 0 }] };
    });
  }
  function removeLaborTier(i) {
    setForm(f => ({ ...f, laborOnlyTiers: (f.laborOnlyTiers || []).filter((_, idx) => idx !== i) }));
  }

  function updateSurcharge(i, key, val) {
    setForm(f => {
      const surcharges = [...f.surcharges];
      surcharges[i] = { ...surcharges[i], [key]: key === 'defaultAmount' ? (parseFloat(val) || 0) : val };
      return { ...f, surcharges };
    });
  }

  function addSurcharge() {
    setForm(f => ({
      ...f,
      surcharges: [
        ...f.surcharges,
        { id: 'custom_' + Date.now(), name: '', defaultAmount: 0, type: 'flat', unit: 'flat' },
      ],
    }));
  }

  function removeSurcharge(i) {
    setForm(f => ({ ...f, surcharges: f.surcharges.filter((_, idx) => idx !== i) }));
  }

  async function save() {
    setSaving(true); setOk(''); setErr('');
    try {
      // Validate tiers
      const tiers = form.pricingTiers.filter(t => t.crewSize >= 1 && t.hourlyRate > 0);
      if (tiers.length === 0) throw new Error('Add at least one crew-size rate.');
      // Labor-only tiers are optional — strip blank/zero rows
      const laborTiers = (form.laborOnlyTiers || []).filter(t => t.crewSize >= 1 && t.hourlyRate > 0);
      // Validate surcharges (strip ones with no name)
      const surcharges = form.surcharges.filter(s => s.name && s.name.trim());

      await window.saveSettings({
        pricingTiers: tiers,
        laborOnlyTiers: laborTiers,
        defaultTripFee: Number(form.defaultTripFee) || 0,
        surcharges,
        minimumHours: Number(form.minimumHours) || 2,
        travelBillingRule: form.travelBillingRule,
        perMileRate: Number(form.perMileRate) || 0,
        // Keep legacy hourly_rate in sync with the smallest-crew tier as a fallback
        hourlyRate: tiers[0]?.hourlyRate || form.hourlyRate,
      });
      setOk('Pricing saved.');
      setTimeout(() => setOk(''), 3000);
    } catch (e) {
      setErr(e.message || 'Failed to save pricing.');
    } finally {
      setSaving(false);
    }
  }

  if (loading || !form) return <div style={{ color: 'var(--muted)' }}>Loading pricing…</div>;

  return (
    <div>
      <Toast kind="ok">{ok}</Toast>
      <Toast kind="err">{err}</Toast>

      <SectionCard title="Hourly rates by crew size" subtitle="One rate for the whole crew — NOT per mover. Estimates pull the rate that matches the crew assigned.">
        <table style={{ width: '100%', borderCollapse: 'collapse', marginBottom: 12 }}>
          <thead>
            <tr style={{ background: 'var(--bg)' }}>
              <th style={pcTh}>Crew size</th>
              <th style={pcTh}>Hourly rate</th>
              <th style={{ ...pcTh, textAlign: 'right' }}></th>
            </tr>
          </thead>
          <tbody>
            {form.pricingTiers.map((t, i) => (
              <tr key={i} style={{ borderTop: '1px solid var(--border)' }}>
                <td style={{ padding: '10px 8px', width: 160 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <SInput type="number" min="1" style={{ width: 70 }} value={t.crewSize} onChange={e => updateTier(i, 'crewSize', e.target.value)} />
                    <span style={{ fontSize: 13, color: 'var(--muted)' }}>movers</span>
                  </div>
                </td>
                <td style={{ padding: '10px 8px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    <span style={{ fontSize: 14, fontWeight: 700, color: 'var(--muted)' }}>$</span>
                    <SInput type="number" min="0" step="0.01" style={{ width: 110 }} value={t.hourlyRate} onChange={e => updateTier(i, 'hourlyRate', e.target.value)} />
                    <span style={{ fontSize: 13, color: 'var(--muted)' }}>/hr</span>
                  </div>
                </td>
                <td style={{ padding: '10px 8px', textAlign: 'right' }}>
                  <button style={S_styles.btnDanger} onClick={() => removeTier(i)} disabled={form.pricingTiers.length <= 1}>Remove</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        <button style={S_styles.btnSecondary} onClick={addTier}>+ Add crew size</button>
      </SectionCard>

      <SectionCard title="Labor-only rates by crew size" subtitle="Used when an estimate is marked as Labor Only (no truck, hands only). Lower than full-service.">
        <table style={{ width: '100%', borderCollapse: 'collapse', marginBottom: 12 }}>
          <thead>
            <tr style={{ background: 'var(--bg)' }}>
              <th style={pcTh}>Crew size</th>
              <th style={pcTh}>Hourly rate</th>
              <th style={{ ...pcTh, textAlign: 'right' }}></th>
            </tr>
          </thead>
          <tbody>
            {(form.laborOnlyTiers || []).map((t, i) => (
              <tr key={i} style={{ borderTop: '1px solid var(--border)' }}>
                <td style={{ padding: '10px 8px', width: 160 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <SInput type="number" min="1" style={{ width: 70 }} value={t.crewSize} onChange={e => updateLaborTier(i, 'crewSize', e.target.value)} />
                    <span style={{ fontSize: 13, color: 'var(--muted)' }}>movers</span>
                  </div>
                </td>
                <td style={{ padding: '10px 8px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    <span style={{ fontSize: 14, fontWeight: 700, color: 'var(--muted)' }}>$</span>
                    <SInput type="number" min="0" step="0.01" style={{ width: 110 }} value={t.hourlyRate} onChange={e => updateLaborTier(i, 'hourlyRate', e.target.value)} />
                    <span style={{ fontSize: 13, color: 'var(--muted)' }}>/hr</span>
                  </div>
                </td>
                <td style={{ padding: '10px 8px', textAlign: 'right' }}>
                  <button style={S_styles.btnDanger} onClick={() => removeLaborTier(i)}>Remove</button>
                </td>
              </tr>
            ))}
            {(!form.laborOnlyTiers || form.laborOnlyTiers.length === 0) && (
              <tr><td colSpan={3} style={{ padding: 12, textAlign: 'center', color: 'var(--muted)', fontSize: 13 }}>No labor-only rates configured. Add at least one if you take labor-only jobs.</td></tr>
            )}
          </tbody>
        </table>
        <button style={S_styles.btnSecondary} onClick={addLaborTier}>+ Add labor-only crew size</button>
      </SectionCard>

      <SectionCard title="Trip Fee default" subtitle="The standard charge added to every new estimate. You can override or waive it per-estimate.">
        <SField label="Default trip fee ($)" hint="Defaults to $50. Set to 0 to start estimates with no trip fee.">
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ fontSize: 14, fontWeight: 700, color: 'var(--muted)' }}>$</span>
            <SInput type="number" min="0" step="0.01" style={{ width: 110 }} value={form.defaultTripFee ?? 50} onChange={e => setForm(f => ({ ...f, defaultTripFee: e.target.value }))} />
          </div>
        </SField>
      </SectionCard>

      <SectionCard title="Billing rules" subtitle="Applied when generating an estimate.">
        <div style={S_styles.row2}>
          <SField label="Minimum billed hours" hint="Minimum time billed even if the job finishes faster.">
            <SInput type="number" min="0" step="0.5" value={form.minimumHours} onChange={e => setForm(f => ({ ...f, minimumHours: e.target.value }))} />
          </SField>
          <SField label="Travel / drive-time billing">
            <SSelect value={form.travelBillingRule} onChange={v => setForm(f => ({ ...f, travelBillingRule: v }))}>
              <option value="double_drive">California double-drive (billed both ways)</option>
              <option value="included">Drive time included (origin → destination only)</option>
              <option value="per_mile">Per-mile rate (see below)</option>
            </SSelect>
          </SField>
        </div>
        {form.travelBillingRule === 'per_mile' && (
          <div style={{ maxWidth: 220 }}>
            <SField label="Per-mile rate">
              <SInput type="number" min="0" step="0.01" value={form.perMileRate} onChange={e => setForm(f => ({ ...f, perMileRate: e.target.value }))} />
            </SField>
          </div>
        )}
      </SectionCard>

      <SectionCard title="Surcharge library" subtitle="Common add-ons. Edit defaults per job as needed.">
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr auto', gap: 8, marginBottom: 6, fontSize: 11, fontWeight: 700, letterSpacing: '0.07em', textTransform: 'uppercase', color: 'var(--muted)' }}>
          <div>Name</div><div>Default amount</div><div>Type</div><div></div>
        </div>
        {form.surcharges.map((s, i) => (
          <div key={i} style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr auto', gap: 8, marginBottom: 8, alignItems: 'center' }}>
            <SInput value={s.name} onChange={e => updateSurcharge(i, 'name', e.target.value)} placeholder="Name (e.g., Stairs)" />
            <SInput type="number" min="0" step="0.01" value={s.defaultAmount} onChange={e => updateSurcharge(i, 'defaultAmount', e.target.value)} />
            <SSelect value={s.type} onChange={v => updateSurcharge(i, 'type', v)}>
              <option value="flat">Flat $</option>
              <option value="per_unit">Per unit</option>
              <option value="per_hour">Per hour</option>
              <option value="percent">Percent %</option>
            </SSelect>
            <button style={S_styles.btnDanger} onClick={() => removeSurcharge(i)}>Remove</button>
          </div>
        ))}
        <button style={{ ...S_styles.btnSecondary, marginTop: 4 }} onClick={addSurcharge}>+ Add surcharge</button>
      </SectionCard>

      <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
        <button style={S_styles.btnPrimary} onClick={save} disabled={saving}>
          {saving ? 'Saving…' : 'Save pricing'}
        </button>
      </div>
    </div>
  );
}

const pcTh = { padding: '10px 8px', textAlign: 'left', fontSize: 11, fontWeight: 700, letterSpacing: '0.07em', textTransform: 'uppercase', color: 'var(--muted)' };

// =============================================================================
// 3. CAPACITY SECTION
// =============================================================================

function CapacitySection() {
  const [form, setForm] = useState(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [ok, setOk] = useState('');
  const [err, setErr] = useState('');

  useEffect(() => {
    window.loadSettings().then(s => { setForm(s); setLoading(false); })
      .catch(e => { setErr(e.message); setLoading(false); });
  }, []);

  async function save() {
    setSaving(true); setOk(''); setErr('');
    try {
      await window.saveSettings({
        avgWeightPerMoverLbs: Number(form.avgWeightPerMoverLbs) || 1500,
        depositPct: Number(form.depositPct) || 0,
        cancellationWindowHours: Number(form.cancellationWindowHours) || 0,
        paymentTermsDays: Number(form.paymentTermsDays) || 0,
      });
      setOk('Capacity & booking rules saved.');
      setTimeout(() => setOk(''), 3000);
    } catch (e) {
      setErr(e.message || 'Failed to save.');
    } finally {
      setSaving(false);
    }
  }

  if (loading || !form) return <div style={{ color: 'var(--muted)' }}>Loading…</div>;

  return (
    <div>
      <Toast kind="ok">{ok}</Toast>
      <Toast kind="err">{err}</Toast>

      <SectionCard title="Crew capacity" subtitle="Used to estimate how much weight a crew can move in a day.">
        <div style={{ maxWidth: 280 }}>
          <SField label="Average weight per mover (lbs)" hint="Industry average is ~1,500 lbs per mover per 8-hour day.">
            <SInput type="number" min="0" value={form.avgWeightPerMoverLbs} onChange={e => setForm(f => ({ ...f, avgWeightPerMoverLbs: e.target.value }))} />
          </SField>
        </div>
      </SectionCard>

      <SectionCard title="Booking & deposits" subtitle="Defaults applied when a customer books a job.">
        <div style={S_styles.row2}>
          <SField label="Required deposit (%)" hint="Percent of job total collected to confirm a booking.">
            <SInput type="number" min="0" max="100" value={form.depositPct} onChange={e => setForm(f => ({ ...f, depositPct: e.target.value }))} />
          </SField>
          <SField label="Cancellation window (hours)" hint="Time before the move when a cancellation no longer qualifies for a full refund.">
            <SInput type="number" min="0" value={form.cancellationWindowHours} onChange={e => setForm(f => ({ ...f, cancellationWindowHours: e.target.value }))} />
          </SField>
        </div>
        <div style={{ maxWidth: 280 }}>
          <SField label="Invoice payment terms (days)" hint="Days from invoice send until payment is due. 0 means due immediately.">
            <SInput type="number" min="0" value={form.paymentTermsDays} onChange={e => setForm(f => ({ ...f, paymentTermsDays: e.target.value }))} />
          </SField>
        </div>
      </SectionCard>

      <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
        <button style={S_styles.btnPrimary} onClick={save} disabled={saving}>
          {saving ? 'Saving…' : 'Save capacity & booking'}
        </button>
      </div>
    </div>
  );
}

// =============================================================================
// 4. DOCUMENTS SECTION
// =============================================================================

function DocumentsSection() {
  const [docs, setDocs] = useState([]);
  const [loading, setLoading] = useState(true);
  const [ok, setOk] = useState('');
  const [err, setErr] = useState('');
  const [editing, setEditing] = useState(null);
  const [uploading, setUploading] = useState(false);
  const fileInputRef = useRef(null);
  const [uploadForm, setUploadForm] = useState({
    title: '',
    category: 'estimate_terms',
    description: '',
    attachToEstimates: true,
    attachToBols: false,
    attachToInvoices: false,
    showInPortal: true,
    requiresSignature: false,
  });
  const [pendingFile, setPendingFile] = useState(null);

  async function refresh() {
    setLoading(true);
    try {
      const list = await window.listDocumentTemplates({ includeInactive: true });
      setDocs(list);
    } catch (e) {
      setErr(e.message);
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => { refresh(); }, []);

  function resetUploadForm() {
    setUploadForm({
      title: '', category: 'estimate_terms', description: '',
      attachToEstimates: true, attachToBols: false, attachToInvoices: false,
      showInPortal: true, requiresSignature: false,
    });
    setPendingFile(null);
    if (fileInputRef.current) fileInputRef.current.value = '';
  }

  async function handleUpload() {
    if (!pendingFile) { setErr('Choose a file first.'); return; }
    if (!uploadForm.title.trim()) { setErr('Enter a title.'); return; }
    setUploading(true); setOk(''); setErr('');
    try {
      await window.uploadDocumentTemplate(pendingFile, uploadForm);
      setOk(`"${uploadForm.title}" uploaded.`);
      setTimeout(() => setOk(''), 3000);
      resetUploadForm();
      await refresh();
    } catch (e) {
      setErr(e.message || 'Upload failed.');
    } finally {
      setUploading(false);
    }
  }

  async function toggleActive(doc) {
    try {
      await window.updateDocumentTemplate(doc.id, { active: !doc.active });
      await refresh();
    } catch (e) { setErr(e.message); }
  }

  async function saveEdit() {
    if (!editing) return;
    try {
      await window.updateDocumentTemplate(editing.id, {
        title: editing.title,
        category: editing.category,
        description: editing.description,
        attachToEstimates: editing.attachToEstimates,
        attachToBols: editing.attachToBols,
        attachToInvoices: editing.attachToInvoices,
        showInPortal: editing.showInPortal,
        requiresSignature: editing.requiresSignature,
      });
      setEditing(null);
      await refresh();
      setOk('Updated.'); setTimeout(() => setOk(''), 2500);
    } catch (e) { setErr(e.message); }
  }

  async function deleteDoc(doc) {
    if (!confirm(`Delete "${doc.title}" permanently? The file will be removed from storage.`)) return;
    try {
      await window.deleteDocumentTemplate(doc.id, { hard: true });
      await refresh();
    } catch (e) { setErr(e.message); }
  }

  async function downloadDoc(doc) {
    try {
      const url = await window.getDocumentDownloadUrl(doc.filePath, 60);
      window.open(url, '_blank');
    } catch (e) { setErr(e.message); }
  }

  const catLabel = id => (window.DOCUMENT_CATEGORIES.find(c => c.id === id) || {}).label || id;
  const fmtKB = b => b < 1024 ? b + ' B' : b < 1048576 ? Math.round(b / 1024) + ' KB' : (b / 1048576).toFixed(1) + ' MB';

  return (
    <div>
      <Toast kind="ok">{ok}</Toast>
      <Toast kind="err">{err}</Toast>

      <SectionCard title="Upload a new document" subtitle="PDFs or Word docs up to 25 MB. Static terms/agreements that get auto-attached to CRM-generated paperwork.">
        <div style={S_styles.row2}>
          <SField label="Title" hint="Shown to customers, e.g. 'MaxAMove Terms of Service 2026'.">
            <SInput value={uploadForm.title} onChange={e => setUploadForm(f => ({ ...f, title: e.target.value }))} placeholder="Terms of Service" />
          </SField>
          <SField label="Category">
            <SSelect value={uploadForm.category} onChange={v => setUploadForm(f => ({ ...f, category: v }))}>
              {(window.DOCUMENT_CATEGORIES || []).map(c => <option key={c.id} value={c.id}>{c.label}</option>)}
            </SSelect>
          </SField>
        </div>
        <SField label="Description (optional)">
          <SInput value={uploadForm.description} onChange={e => setUploadForm(f => ({ ...f, description: e.target.value }))} placeholder="Short description of what this document is." />
        </SField>
        <SField label="Where does this auto-attach?">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            <SCheck checked={uploadForm.attachToEstimates} onChange={v => setUploadForm(f => ({ ...f, attachToEstimates: v }))} label="Append to every estimate PDF" />
            <SCheck checked={uploadForm.attachToBols}      onChange={v => setUploadForm(f => ({ ...f, attachToBols: v }))}      label="Append to every Bill of Lading" />
            <SCheck checked={uploadForm.attachToInvoices}  onChange={v => setUploadForm(f => ({ ...f, attachToInvoices: v }))}  label="Append to every invoice" />
            <SCheck checked={uploadForm.showInPortal}      onChange={v => setUploadForm(f => ({ ...f, showInPortal: v }))}      label="Show in the customer portal" />
            <SCheck checked={uploadForm.requiresSignature} onChange={v => setUploadForm(f => ({ ...f, requiresSignature: v }))} label="Requires customer signature" />
          </div>
        </SField>
        <SField label="File">
          <input
            ref={fileInputRef}
            type="file"
            accept=".pdf,.doc,.docx,.png,.jpg,.jpeg,.webp"
            onChange={e => setPendingFile(e.target.files[0] || null)}
            style={{ fontSize: 13 }}
          />
          {pendingFile && <div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 4 }}>{pendingFile.name} · {fmtKB(pendingFile.size)}</div>}
        </SField>
        <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
          <button style={S_styles.btnSecondary} onClick={resetUploadForm} disabled={uploading}>Clear</button>
          <button style={S_styles.btnPrimary} onClick={handleUpload} disabled={uploading || !pendingFile}>
            {uploading ? 'Uploading…' : 'Upload document'}
          </button>
        </div>
      </SectionCard>

      <SectionCard title="Your documents" subtitle={`${docs.length} total · ${docs.filter(d => d.active).length} active`}>
        {loading ? <div style={{ color: 'var(--muted)' }}>Loading…</div>
          : docs.length === 0 ? <div style={{ color: 'var(--muted)', fontSize: 13 }}>No documents yet. Upload one above.</div>
          : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {docs.map(doc => (
                <div key={doc.id} style={{ border: '1px solid var(--border)', borderRadius: 10, padding: 14, background: doc.active ? 'var(--card)' : 'var(--bg)', opacity: doc.active ? 1 : 0.65 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
                        <div style={{ fontWeight: 700, fontSize: 14 }}>{doc.title}</div>
                        <span style={{ ...S_styles.pill, background: '#f0fdfb', color: 'var(--accent-dark)' }}>{catLabel(doc.category)}</span>
                        {!doc.active && <span style={{ ...S_styles.pill, background: '#f1f5f9', color: '#64748b' }}>Disabled</span>}
                      </div>
                      {doc.description && <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 4 }}>{doc.description}</div>}
                      <div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 6, display: 'flex', gap: 10, flexWrap: 'wrap' }}>
                        <span>{doc.fileName}</span>
                        <span>·</span>
                        <span>{fmtKB(doc.fileSize)}</span>
                        {doc.attachToEstimates && <span style={{display:'inline-flex',alignItems:'center',gap:4}}>· <Icon name="clipboard" size={11}/> Estimates</span>}
                        {doc.attachToBols && <span style={{display:'inline-flex',alignItems:'center',gap:4}}>· <Icon name="file-text" size={11}/> BOLs</span>}
                        {doc.attachToInvoices && <span style={{display:'inline-flex',alignItems:'center',gap:4}}>· <Icon name="receipt" size={11}/> Invoices</span>}
                        {doc.showInPortal && <span style={{display:'inline-flex',alignItems:'center',gap:4}}>· <Icon name="user" size={11}/> Portal</span>}
                        {doc.requiresSignature && <span style={{display:'inline-flex',alignItems:'center',gap:4}}>· <Icon name="signature" size={11}/> Signature</span>}
                      </div>
                    </div>
                    <div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
                      <button style={S_styles.btnSecondary} onClick={() => downloadDoc(doc)}>View</button>
                      <button style={S_styles.btnSecondary} onClick={() => setEditing({ ...doc })}>Edit</button>
                      <button style={S_styles.btnSecondary} onClick={() => toggleActive(doc)}>{doc.active ? 'Disable' : 'Enable'}</button>
                      <button style={S_styles.btnDanger} onClick={() => deleteDoc(doc)}>Delete</button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
      </SectionCard>

      {/* Edit modal */}
      {editing && (
        <div onClick={() => setEditing(null)} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.5)', zIndex: 200, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
          <div onClick={e => e.stopPropagation()} style={{ background: '#fff', borderRadius: 16, padding: 24, maxWidth: 540, width: '100%', maxHeight: '90vh', overflowY: 'auto', boxShadow: '0 24px 60px rgba(0,0,0,.2)' }}>
            <div style={{ fontWeight: 800, fontSize: 16, fontFamily: 'Poppins', marginBottom: 14 }}>Edit document</div>
            <SField label="Title"><SInput value={editing.title} onChange={e => setEditing(d => ({ ...d, title: e.target.value }))} /></SField>
            <SField label="Category">
              <SSelect value={editing.category} onChange={v => setEditing(d => ({ ...d, category: v }))}>
                {(window.DOCUMENT_CATEGORIES || []).map(c => <option key={c.id} value={c.id}>{c.label}</option>)}
              </SSelect>
            </SField>
            <SField label="Description">
              <SInput value={editing.description} onChange={e => setEditing(d => ({ ...d, description: e.target.value }))} />
            </SField>
            <SField label="Auto-attach rules">
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                <SCheck checked={editing.attachToEstimates} onChange={v => setEditing(d => ({ ...d, attachToEstimates: v }))} label="Estimates" />
                <SCheck checked={editing.attachToBols}      onChange={v => setEditing(d => ({ ...d, attachToBols: v }))}      label="Bills of Lading" />
                <SCheck checked={editing.attachToInvoices}  onChange={v => setEditing(d => ({ ...d, attachToInvoices: v }))}  label="Invoices" />
                <SCheck checked={editing.showInPortal}      onChange={v => setEditing(d => ({ ...d, showInPortal: v }))}      label="Customer portal" />
                <SCheck checked={editing.requiresSignature} onChange={v => setEditing(d => ({ ...d, requiresSignature: v }))} label="Requires signature" />
              </div>
            </SField>
            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 12 }}>
              <button style={S_styles.btnSecondary} onClick={() => setEditing(null)}>Cancel</button>
              <button style={S_styles.btnPrimary} onClick={saveEdit}>Save changes</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// =============================================================================
// 5. MY PROFILE SECTION
// =============================================================================

function MyProfileSection() {
  const [profile, setProfile] = useState(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [ok, setOk] = useState('');
  const [err, setErr] = useState('');
  const [pw, setPw] = useState({ new1: '', new2: '' });
  const [pwBusy, setPwBusy] = useState(false);

  useEffect(() => {
    window.loadMyProfile().then(p => { setProfile(p); setLoading(false); })
      .catch(e => { setErr(e.message); setLoading(false); });
  }, []);

  async function saveProfile() {
    setSaving(true); setOk(''); setErr('');
    try {
      const p = await window.saveMyProfile({
        fullName: profile.fullName,
        phone: profile.phone,
      });
      setProfile(p);
      setOk('Profile saved.');
      setTimeout(() => setOk(''), 3000);
    } catch (e) {
      setErr(e.message || 'Failed to save.');
    } finally {
      setSaving(false);
    }
  }

  async function savePassword() {
    if (!pw.new1 || pw.new1 !== pw.new2) { setErr('Passwords must match.'); return; }
    if (pw.new1.length < 6) { setErr('Password must be at least 6 characters.'); return; }
    setPwBusy(true); setErr(''); setOk('');
    try {
      await window.changeMyPassword(pw.new1);
      setOk('Password updated.');
      setPw({ new1: '', new2: '' });
      setTimeout(() => setOk(''), 3000);
    } catch (e) {
      setErr(e.message || 'Failed to change password.');
    } finally {
      setPwBusy(false);
    }
  }

  async function signOut() {
    if (!confirm('Sign out of MaxAMove?')) return;
    await window.signOut();
  }

  if (loading || !profile) return <div style={{ color: 'var(--muted)' }}>Loading your profile…</div>;

  const roleLabel = {
    owner: 'Owner', staff: 'Staff', crew: 'Crew', customer: 'Customer', viewer: 'Viewer',
  }[profile.role] || profile.role;

  return (
    <div>
      <Toast kind="ok">{ok}</Toast>
      <Toast kind="err">{err}</Toast>

      <SectionCard title="Your info" subtitle="Appears in audit logs and 'logged in as' displays.">
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 18 }}>
          <div style={{ width: 60, height: 60, borderRadius: '50%', background: 'linear-gradient(135deg,#14C6BF,#3DCC7E)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, fontSize: 22, fontFamily: 'Poppins' }}>
            {(profile.fullName || profile.email || '?').split(/\s+/).slice(0, 2).map(s => s[0]).join('').toUpperCase()}
          </div>
          <div>
            <div style={{ fontWeight: 800, fontSize: 16, fontFamily: 'Poppins' }}>{profile.fullName || 'Unnamed'}</div>
            <div style={{ fontSize: 13, color: 'var(--muted)' }}>{profile.email}</div>
            <div style={{ marginTop: 4 }}>
              <span style={{ ...S_styles.pill, background: 'var(--accent-light)', color: 'var(--accent-dark)' }}>{roleLabel}</span>
            </div>
          </div>
        </div>
        <div style={S_styles.row2}>
          <SField label="Full name">
            <SInput value={profile.fullName} onChange={e => setProfile(p => ({ ...p, fullName: e.target.value }))} />
          </SField>
          <SField label="Phone">
            <SInput value={profile.phone} onChange={e => setProfile(p => ({ ...p, phone: e.target.value }))} placeholder="(555) 123-4567" />
          </SField>
        </div>
        <SField label="Email">
          <SInput value={profile.email} disabled hint="Email is managed by auth — can't be edited here." />
        </SField>
        <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
          <button style={S_styles.btnPrimary} onClick={saveProfile} disabled={saving}>{saving ? 'Saving…' : 'Save profile'}</button>
        </div>
      </SectionCard>

      <SectionCard title="Change password">
        <div style={S_styles.row2}>
          <SField label="New password">
            <SInput type="password" value={pw.new1} onChange={e => setPw({ ...pw, new1: e.target.value })} />
          </SField>
          <SField label="Confirm new password">
            <SInput type="password" value={pw.new2} onChange={e => setPw({ ...pw, new2: e.target.value })} />
          </SField>
        </div>
        <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
          <button style={S_styles.btnPrimary} onClick={savePassword} disabled={pwBusy}>{pwBusy ? 'Updating…' : 'Update password'}</button>
        </div>
      </SectionCard>

      <SectionCard title="Session">
        <button style={S_styles.btnDanger} onClick={signOut}>Sign out</button>
      </SectionCard>
    </div>
  );
}

// =============================================================================
// 6. TEAM SECTION (owner-only)
// =============================================================================

function TeamSection({ myRole }) {
  const [members, setMembers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [err, setErr] = useState('');
  const [ok, setOk] = useState('');

  async function refresh() {
    setLoading(true);
    try {
      const list = await window.listTeamMembers();
      setMembers(list);
    } catch (e) {
      setErr(e.message);
    } finally {
      setLoading(false);
    }
  }
  useEffect(() => { refresh(); }, []);

  async function changeRole(userId, newRole) {
    if (!confirm(`Change this user's role to "${newRole}"?`)) return;
    try {
      await window.updateTeamMemberRole(userId, newRole);
      await refresh();
      setOk('Role updated.'); setTimeout(() => setOk(''), 2500);
    } catch (e) { setErr(e.message); }
  }

  async function toggleActive(m) {
    const verb = m.active ? 'Deactivate' : 'Reactivate';
    if (!confirm(`${verb} ${m.fullName || m.email}?`)) return;
    try {
      await window.setTeamMemberActive(m.id, !m.active);
      await refresh();
    } catch (e) { setErr(e.message); }
  }

  if (myRole !== 'owner') {
    return <div style={{ color: 'var(--muted)', fontSize: 13 }}>Only the owner can manage the team.</div>;
  }

  return (
    <div>
      <Toast kind="ok">{ok}</Toast>
      <Toast kind="err">{err}</Toast>

      <SectionCard title="All accounts" subtitle={`${members.length} total — anyone who has signed up appears here. Invitations & email sends are a future feature.`}>
        {loading ? <div style={{ color: 'var(--muted)' }}>Loading…</div>
          : members.length === 0 ? <div style={{ color: 'var(--muted)' }}>No accounts yet.</div>
          : (
            <div style={{ overflowX: 'auto' }}>
              <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
                <thead>
                  <tr style={{ background: 'var(--bg)' }}>
                    {['Name', 'Email', 'Role', 'Status', ''].map(h => <th key={h} style={pcTh}>{h}</th>)}
                  </tr>
                </thead>
                <tbody>
                  {members.map(m => (
                    <tr key={m.id} style={{ borderTop: '1px solid var(--border)' }}>
                      <td style={{ padding: '12px 8px', fontWeight: 700 }}>{m.fullName || '—'}</td>
                      <td style={{ padding: '12px 8px', color: 'var(--muted)' }}>{m.email}</td>
                      <td style={{ padding: '12px 8px' }}>
                        <SSelect value={m.role} onChange={v => changeRole(m.id, v)} style={{ padding: '6px 10px', fontSize: 12 }}>
                          <option value="owner">Owner</option>
                          <option value="staff">Staff</option>
                          <option value="crew">Crew</option>
                          <option value="customer">Customer</option>
                          <option value="viewer">Viewer</option>
                        </SSelect>
                      </td>
                      <td style={{ padding: '12px 8px' }}>
                        <span style={{ ...S_styles.pill, background: m.active ? '#f0fdf4' : '#fef2f2', color: m.active ? '#166534' : '#b91c1c' }}>
                          {m.active ? 'Active' : 'Disabled'}
                        </span>
                      </td>
                      <td style={{ padding: '12px 8px', textAlign: 'right' }}>
                        <button style={S_styles.btnSecondary} onClick={() => toggleActive(m)}>
                          {m.active ? 'Deactivate' : 'Reactivate'}
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
      </SectionCard>
    </div>
  );
}

// =============================================================================
// 7. CREW MEMBERS SECTION (owner + staff)
// =============================================================================

function CrewSection({ myRole }) {
  const [crew, setCrew] = useState([]);
  const [loading, setLoading] = useState(true);
  const [err, setErr] = useState('');
  const [ok, setOk] = useState('');
  const [editing, setEditing] = useState(null);
  const [showAdvanced, setShowAdvanced] = useState(false);
  // Per-member transient UI state for the Crew HQ portal-access actions.
  const [copiedFor, setCopiedFor] = useState({});
  const [generatingFor, setGeneratingFor] = useState({});

  const canEdit = myRole === 'owner' || myRole === 'staff';

  async function handleGeneratePortal(m) {
    const subject = m.email ? `${m.name} (${m.email})` : `${m.name} (no email — we'll create an internal sign-in for them)`;
    if (!confirm(`Generate Crew HQ access for ${subject}?\n\nThis creates their sign-in account and gives you a one-tap link to share.`)) return;
    setGeneratingFor(s => ({ ...s, [m.id]: true }));
    try {
      const r = await window.ensureWorkerPortalAccess(m);
      await refresh();
      if (r.existed) {
        setOk(`Generated link for ${m.name}. Heads up: an auth account already existed for them. If they can't sign in, reset their password in Supabase → Authentication.`);
      } else {
        setOk(`Crew HQ access ready for ${m.name}. Tap "Copy Link" to share.`);
      }
      setTimeout(() => setOk(''), 5000);
    } catch (e) {
      setErr(e.message || 'Could not generate portal access.');
    } finally {
      setGeneratingFor(s => ({ ...s, [m.id]: false }));
    }
  }

  function handleViewPortal(m) {
    // Owner-side preview: opens worker.html in a new tab AS the crew member
    // would see it, but using your existing CRM session — no auto-signin
    // identity flip, no impact on the crew member's stored password.
    const url = new URL('worker.html', window.location.href);
    url.hash = 'preview=' + m.id;
    window.open(url.href, '_blank', 'noopener');
  }

  async function handleCopyPortal(m) {
    const link = window.getWorkerPortalLink(m);
    if (!link) return;
    try {
      await navigator.clipboard.writeText(link);
      setCopiedFor(s => ({ ...s, [m.id]: true }));
      setTimeout(() => setCopiedFor(s => ({ ...s, [m.id]: false })), 1800);
    } catch {
      // Fallback: show prompt
      window.prompt('Copy this link:', link);
    }
  }

  async function refresh() {
    setLoading(true);
    try {
      const list = await window.listCrew({ includeInactive: true });
      setCrew(list);
    } catch (e) {
      setErr(e.message);
    } finally {
      setLoading(false);
    }
  }
  useEffect(() => { refresh(); }, []);

  function startNew() {
    setEditing({
      id: null, name: '', role: 'mover', phone: '', email: '',
      hourlyRate: 25, active: true, capacityWeightLbs: null, notes: '',
      lbsPerHourBaseline: window.DEFAULT_LBS_PER_HOUR_PER_MOVER || 382,
    });
  }

  async function saveEdit() {
    if (!editing.name?.trim()) { setErr('Name is required.'); return; }
    try {
      if (editing.id) {
        await window.updateCrewMember(editing.id, {
          name: editing.name, role: editing.role, phone: editing.phone, email: editing.email,
          hourlyRate: editing.hourlyRate, active: editing.active,
          capacityWeightLbs: editing.capacityWeightLbs, notes: editing.notes,
          lbsPerHourBaseline: editing.lbsPerHourBaseline,
        });
      } else {
        await window.createCrewMember({
          name: editing.name, role: editing.role, phone: editing.phone, email: editing.email,
          hourlyRate: editing.hourlyRate, active: editing.active,
          capacityWeightLbs: editing.capacityWeightLbs, notes: editing.notes,
          lbsPerHourBaseline: editing.lbsPerHourBaseline,
        });
      }
      setEditing(null);
      await refresh();
      setOk('Saved.'); setTimeout(() => setOk(''), 2500);
    } catch (e) { setErr(e.message); }
  }

  async function toggleActive(m) {
    try {
      await window.updateCrewMember(m.id, { active: !m.active });
      await refresh();
    } catch (e) { setErr(e.message); }
  }

  if (!canEdit) {
    return <div style={{ color: 'var(--muted)', fontSize: 13 }}>Only owner and staff can manage the crew.</div>;
  }

  return (
    <div>
      <Toast kind="ok">{ok}</Toast>
      <Toast kind="err">{err}</Toast>

      <SectionCard
        title="Crew members"
        subtitle={`${crew.filter(c => c.active).length} active · ${crew.length} total`}
        action={<button style={S_styles.btnPrimary} onClick={startNew}>+ Add crew member</button>}
      >
        {loading ? <div style={{ color: 'var(--muted)' }}>Loading…</div>
          : crew.length === 0 ? <div style={{ color: 'var(--muted)', fontSize: 13 }}>No crew yet. Click "+ Add crew member" to start.</div>
          : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {crew.map(m => (
                <div key={m.id} style={{ display: 'flex', flexDirection: 'column', gap: 10, padding: 12, border: '1px solid var(--border)', borderRadius: 10, background: m.active ? 'var(--card)' : 'var(--bg)', opacity: m.active ? 1 : 0.65 }}>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 12, minWidth: 0 }}>
                      <div style={{ width: 40, height: 40, borderRadius: '50%', background: 'var(--accent)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, fontSize: 13, flexShrink: 0 }}>{m.avatar}</div>
                      <div style={{ minWidth: 0 }}>
                        <div style={{ fontWeight: 700, fontSize: 14, display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                          {m.name}
                          {m.portalPassword && <span title="Crew HQ access generated" style={{ fontSize: 9, fontWeight: 800, padding: '2px 6px', borderRadius: 4, background: 'var(--accent-light)', color: 'var(--accent-dark)', letterSpacing: '.05em' }}>HQ</span>}
                        </div>
                        <div style={{ fontSize: 11, color: 'var(--muted)', display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                          <span>{({lead:'Lead Mover', mover:'Mover', helper:'Helper'}[m.role] || m.role)}</span>
                          {m.hourlyRate != null && <><span>·</span><span>${m.hourlyRate}/hr pay</span></>}
                          {(m.lbsPerHourLearned != null || m.lbsPerHourBaseline != null) && (
                            <>
                              <span>·</span>
                              <span title={m.lbsPerHourLearned != null ? `Baseline: ${m.lbsPerHourBaseline} · Learned from ${m.jobsAnalyzedCount} job(s)` : 'Baseline (no completed jobs analyzed yet)'}>
                                {m.lbsPerHourLearned != null
                                  ? <span style={{display:'inline-flex',alignItems:'center',gap:4}}><Icon name="trending-up" size={11}/> <b style={{ color: 'var(--accent-dark)' }}>{m.lbsPerHourLearned}</b> lbs/hr ({m.jobsAnalyzedCount}j)</span>
                                  : <span style={{display:'inline-flex',alignItems:'center',gap:4}}><Icon name="chart-bar" size={11}/> {m.lbsPerHourBaseline} lbs/hr (baseline)</span>}
                              </span>
                            </>
                          )}
                          {m.phone && <><span>·</span><span>{m.phone}</span></>}
                          {m.email && <><span>·</span><span>{m.email}</span></>}
                        </div>
                      </div>
                    </div>
                    <div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
                      <button style={S_styles.btnSecondary} onClick={() => setEditing({ ...m })}>Edit</button>
                      <button style={S_styles.btnSecondary} onClick={() => toggleActive(m)}>{m.active ? 'Deactivate' : 'Reactivate'}</button>
                    </div>
                  </div>

                  {/* Crew HQ portal access — View Portal is always available
                      (owner-side preview, uses your own session). Generate /
                      Copy Link manage the crew member's actual auto-login link. */}
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, paddingTop: 8, borderTop: '1px dashed var(--border-soft)', flexWrap: 'wrap' }}>
                    <span style={{ fontSize: 10, fontWeight: 800, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '.08em' }}>Crew HQ</span>
                    <span style={{ fontSize: 11, color: m.portalPassword ? 'var(--accent-dark)' : 'var(--muted)', fontWeight: m.portalPassword ? 700 : 400, flex: 1 }}>
                      {m.portalPassword ? 'One-tap link ready.' : 'Access not generated yet — preview still works.'}
                    </span>
                    <button
                      style={{ ...S_styles.btnSecondary, fontSize: 11, padding: '6px 10px' }}
                      onClick={() => handleViewPortal(m)}
                      title="Preview their portal in a new tab using your own session">
                      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}><Icon name="eye" size={11}/> View Portal</span>
                    </button>
                    {m.portalPassword ? (
                      <button
                        style={{ ...S_styles.btnSecondary, fontSize: 11, padding: '6px 10px' }}
                        onClick={() => handleCopyPortal(m)}
                        title="Copy the crew member's one-tap sign-in link">
                        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
                          <Icon name={copiedFor[m.id] ? 'check' : 'send'} size={11}/>
                          {copiedFor[m.id] ? 'Copied!' : 'Copy Link'}
                        </span>
                      </button>
                    ) : (
                      <button
                        style={{ ...S_styles.btnSecondary, fontSize: 11, padding: '6px 10px', opacity: generatingFor[m.id] ? 0.55 : 1 }}
                        disabled={!!generatingFor[m.id]}
                        onClick={() => handleGeneratePortal(m)}>
                        {generatingFor[m.id] ? 'Generating…' : <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}><Icon name="bolt" size={11}/> Generate access</span>}
                      </button>
                    )}
                  </div>
                </div>
              ))}
            </div>
          )}
      </SectionCard>

      {/* Edit / Create modal */}
      {editing && (
        <div onClick={() => setEditing(null)} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.5)', zIndex: 200, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
          <div onClick={e => e.stopPropagation()} style={{ background: '#fff', borderRadius: 16, padding: 24, maxWidth: 560, width: '100%', maxHeight: '90vh', overflowY: 'auto', boxShadow: '0 24px 60px rgba(0,0,0,.2)' }}>
            <div style={{ fontWeight: 800, fontSize: 16, fontFamily: 'Poppins', marginBottom: 14 }}>
              {editing.id ? 'Edit crew member' : 'Add crew member'}
            </div>
            <div style={S_styles.row2}>
              <SField label="Full name">
                <SInput value={editing.name} onChange={e => setEditing(d => ({ ...d, name: e.target.value }))} />
              </SField>
              <SField label="Role">
                <SSelect value={editing.role} onChange={v => setEditing(d => ({ ...d, role: v }))}>
                  <option value="lead">Lead Mover</option>
                  <option value="mover">Mover</option>
                  <option value="helper">Helper</option>
                </SSelect>
              </SField>
            </div>
            <div style={S_styles.row2}>
              <SField label="Phone">
                <SInput value={editing.phone || ''} onChange={e => setEditing(d => ({ ...d, phone: e.target.value }))} />
              </SField>
              <SField label="Email">
                <SInput value={editing.email || ''} onChange={e => setEditing(d => ({ ...d, email: e.target.value }))} />
              </SField>
            </div>
            <div style={S_styles.row2}>
              <SField label="Hourly pay rate">
                <SInput type="number" min="0" step="0.01" value={editing.hourlyRate ?? ''} onChange={e => setEditing(d => ({ ...d, hourlyRate: parseFloat(e.target.value) || 0 }))} />
              </SField>
              <SField label="Status">
                <SSelect value={editing.active ? 'active' : 'inactive'} onChange={v => setEditing(d => ({ ...d, active: v === 'active' }))}>
                  <option value="active">Active</option>
                  <option value="inactive">Inactive</option>
                </SSelect>
              </SField>
            </div>

            <SField
              label="Throughput baseline (lbs/hr this mover can move)"
              hint={`Default: ${window.DEFAULT_LBS_PER_HOUR_PER_MOVER || 382} lbs/hr (calibrated to MaxAMove). The system will refine this from real job data over time. Combined crew throughput = sum of each mover's rate.`}>
              <SInput
                type="number" min="0" step="1"
                value={editing.lbsPerHourBaseline ?? ''}
                onChange={e => setEditing(d => ({ ...d, lbsPerHourBaseline: e.target.value === '' ? null : parseFloat(e.target.value) || 0 }))}
                placeholder={String(window.DEFAULT_LBS_PER_HOUR_PER_MOVER || 382)} />
            </SField>
            {editing.id && editing.lbsPerHourLearned != null && (
              <div style={{ marginTop: -4, marginBottom: 12, padding: '8px 12px', background: 'var(--accent-light)', borderRadius: 8, fontSize: 11, color: 'var(--accent-dark)', display: 'flex', alignItems: 'flex-start', gap: 6 }}>
                <Icon name="trending-up" size={13} style={{flexShrink:0,marginTop:1}}/>
                <div><b>Learned rate:</b> {editing.lbsPerHourLearned} lbs/hr (from {editing.jobsAnalyzedCount} completed job{editing.jobsAnalyzedCount !== 1 ? 's' : ''}).
                The estimator uses the learned rate when it exists, falling back to your baseline.</div>
              </div>
            )}

            <button type="button" style={{ ...S_styles.btnSecondary, width: '100%', marginBottom: 12 }} onClick={() => setShowAdvanced(s => !s)}>
              {showAdvanced ? '▾ Hide advanced' : '▸ Advanced (capacity override & notes)'}
            </button>

            {showAdvanced && (
              <>
                <SField label="Per-mover weight capacity override (lbs)" hint="Leave blank to use the company default from Capacity settings. Future: auto-calculate from job history.">
                  <SInput type="number" min="0" value={editing.capacityWeightLbs ?? ''} onChange={e => setEditing(d => ({ ...d, capacityWeightLbs: e.target.value === '' ? null : parseFloat(e.target.value) }))} placeholder="Default" />
                </SField>
                <SField label="Internal notes">
                  <STextarea value={editing.notes || ''} onChange={e => setEditing(d => ({ ...d, notes: e.target.value }))} placeholder="Only visible to owner/staff." />
                </SField>
              </>
            )}

            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 12 }}>
              <button style={S_styles.btnSecondary} onClick={() => setEditing(null)}>Cancel</button>
              <button style={S_styles.btnPrimary} onClick={saveEdit}>{editing.id ? 'Save' : 'Create'}</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// =============================================================================
// 8. TRUCKS SECTION (owner + staff)
// =============================================================================

function TrucksSection({ myRole }) {
  const [trucks, setTrucks] = useState([]);
  const [presets, setPresets] = useState([]);
  const [loading, setLoading] = useState(true);
  const [err, setErr] = useState('');
  const [ok, setOk] = useState('');
  const [editing, setEditing] = useState(null);

  const canEdit = myRole === 'owner' || myRole === 'staff';

  async function refresh() {
    setLoading(true);
    try {
      const [list, sizes] = await Promise.all([
        window.listTrucks(),
        window.listTruckSizePresets(),
      ]);
      setTrucks(list);
      setPresets(sizes);
    } catch (e) {
      setErr(e.message);
    } finally {
      setLoading(false);
    }
  }
  useEffect(() => { refresh(); }, []);

  function startNew() {
    setEditing({
      id: null, name: '', size: '', plate: '',
      capacityCuft: 1000, capacityLbs: 9000,
      mileage: 0, status: 'available', nextService: null, notes: '',
    });
  }

  function applyPreset(presetId) {
    const p = presets.find(x => x.id === presetId);
    if (!p || !editing) return;
    setEditing({ ...editing, size: p.label.replace(/\s+Truck$/i, '').trim(), capacityCuft: p.capacityCuft, capacityLbs: p.capacityLbs });
  }

  async function saveEdit() {
    if (!editing.name?.trim()) { setErr('Truck name is required.'); return; }
    try {
      if (editing.id) {
        await window.updateTruck(editing.id, {
          name: editing.name, size: editing.size, plate: editing.plate,
          status: editing.status, mileage: editing.mileage,
          capacityCuft: editing.capacityCuft, capacityLbs: editing.capacityLbs,
          nextService: editing.nextService, notes: editing.notes,
        });
      } else {
        await window.createTruck({
          name: editing.name, size: editing.size, plate: editing.plate,
          status: editing.status, mileage: editing.mileage,
          capacityCuft: editing.capacityCuft, capacityLbs: editing.capacityLbs,
          nextService: editing.nextService, notes: editing.notes,
        });
      }
      setEditing(null);
      await refresh();
      setOk('Saved.'); setTimeout(() => setOk(''), 2500);
    } catch (e) { setErr(e.message); }
  }

  async function changeStatus(truck, status) {
    try {
      await window.updateTruck(truck.id, { status });
      await refresh();
    } catch (e) { setErr(e.message); }
  }

  if (!canEdit) {
    return <div style={{ color: 'var(--muted)', fontSize: 13 }}>Only owner and staff can manage trucks.</div>;
  }

  const statusMap = {
    available: { bg: '#f0fdf4', color: '#16a34a', label: 'Available' },
    deployed: { bg: '#fff7ed', color: '#f97316', label: 'Deployed' },
    maintenance: { bg: '#fef2f2', color: '#ef4444', label: 'Maintenance' },
    'out-of-service': { bg: '#f3f4f6', color: '#6b7280', label: 'Out of service' },
  };

  return (
    <div>
      <Toast kind="ok">{ok}</Toast>
      <Toast kind="err">{err}</Toast>

      <SectionCard
        title="Trucks & capacity"
        subtitle="Each truck has a name + cubic-footage capacity. The estimate inventory step warns you when total cubic footage exceeds the assigned truck's capacity."
        action={<button style={S_styles.btnPrimary} onClick={startNew}>+ Add truck</button>}
      >
        {loading ? <div style={{ color: 'var(--muted)' }}>Loading…</div>
          : trucks.length === 0 ? <div style={{ color: 'var(--muted)', fontSize: 13 }}>No trucks yet. Click "+ Add truck" to set up your fleet.</div>
          : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {trucks.map(t => {
                const s = statusMap[t.status] || statusMap.available;
                return (
                  <div key={t.id} style={{ border: '1px solid var(--border)', borderRadius: 10, padding: 14, background: 'var(--card)' }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12, flexWrap: 'wrap' }}>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
                          <span style={{ fontWeight: 700, fontSize: 14 }}>{t.name}</span>
                          {t.size && <span style={{ ...S_styles.pill, background: '#eff6ff', color: '#1e40af' }}>{t.size}</span>}
                          <span style={{ ...S_styles.pill, background: s.bg, color: s.color }}>{s.label}</span>
                        </div>
                        <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 4, display: 'flex', gap: 12, flexWrap: 'wrap' }}>
                          {t.plate && <span style={{display:'inline-flex',alignItems:'center',gap:4}}><Icon name="credit-card" size={12}/> {t.plate}</span>}
                          {t.capacityCuft && <span style={{display:'inline-flex',alignItems:'center',gap:4}}><Icon name="box" size={12}/> {t.capacityCuft.toLocaleString()} cu ft</span>}
                          {t.capacityLbs && <span style={{display:'inline-flex',alignItems:'center',gap:4}}><Icon name="ruler" size={12}/> {t.capacityLbs.toLocaleString()} lbs</span>}
                          {t.mileage > 0 && <span style={{display:'inline-flex',alignItems:'center',gap:4}}><Icon name="road" size={12}/> {t.mileage.toLocaleString()} mi</span>}
                          {t.nextService && <span style={{display:'inline-flex',alignItems:'center',gap:4}}><Icon name="wrench" size={12}/> service: {window.fmtShortDate(t.nextService)}</span>}
                        </div>
                        {t.notes && <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 4, fontStyle: 'italic' }}>{t.notes}</div>}
                      </div>
                      <div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
                        <SSelect value={t.status} onChange={v => changeStatus(t, v)} style={{ padding: '6px 10px', fontSize: 12, width: 'auto' }}>
                          <option value="available">Available</option>
                          <option value="deployed">Deployed</option>
                          <option value="maintenance">Maintenance</option>
                          <option value="out-of-service">Out of service</option>
                        </SSelect>
                        <button style={S_styles.btnSecondary} onClick={() => setEditing({ ...t })}>Edit</button>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
      </SectionCard>

      {editing && (
        <div onClick={() => setEditing(null)} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.5)', zIndex: 200, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
          <div onClick={e => e.stopPropagation()} style={{ background: '#fff', borderRadius: 16, padding: 24, maxWidth: 580, width: '100%', maxHeight: '90vh', overflowY: 'auto', boxShadow: '0 24px 60px rgba(0,0,0,.2)' }}>
            <div style={{ fontWeight: 800, fontSize: 16, fontFamily: 'Poppins', marginBottom: 14 }}>
              {editing.id ? 'Edit truck' : 'Add truck'}
            </div>

            <div style={S_styles.row2}>
              <SField label="Truck name" hint="E.g. 'Truck #2', 'White Box Truck'.">
                <SInput value={editing.name} onChange={e => setEditing(d => ({ ...d, name: e.target.value }))} />
              </SField>
              <SField label="License plate">
                <SInput value={editing.plate || ''} onChange={e => setEditing(d => ({ ...d, plate: e.target.value }))} placeholder="ABC-1234" />
              </SField>
            </div>

            <SField label="Size preset (optional shortcut)" hint="Picking a preset fills in the size label and capacity. You can still adjust below.">
              <SSelect value="" onChange={v => v && applyPreset(v)}>
                <option value="">— Apply a preset —</option>
                {presets.map(p => <option key={p.id} value={p.id}>{p.label} — {p.capacityCuft.toLocaleString()} cu ft / {p.capacityLbs.toLocaleString()} lbs</option>)}
              </SSelect>
            </SField>

            <div style={S_styles.row2}>
              <SField label="Size label" hint="Free-text — e.g. '20 ft', '26 ft', 'Cargo Van'.">
                <SInput value={editing.size || ''} onChange={e => setEditing(d => ({ ...d, size: e.target.value }))} placeholder="20 ft" />
              </SField>
              <SField label="Status">
                <SSelect value={editing.status} onChange={v => setEditing(d => ({ ...d, status: v }))}>
                  <option value="available">Available</option>
                  <option value="deployed">Deployed</option>
                  <option value="maintenance">Maintenance</option>
                  <option value="out-of-service">Out of service</option>
                </SSelect>
              </SField>
            </div>

            <div style={S_styles.row2}>
              <SField label="Cubic-feet capacity" hint="Total interior cargo volume in cubic feet.">
                <SInput type="number" min="0" value={editing.capacityCuft || ''} onChange={e => setEditing(d => ({ ...d, capacityCuft: parseFloat(e.target.value) || 0 }))} />
              </SField>
              <SField label="Weight capacity (lbs)" hint="Total payload capacity (truck weight limit minus tare).">
                <SInput type="number" min="0" value={editing.capacityLbs || ''} onChange={e => setEditing(d => ({ ...d, capacityLbs: parseFloat(e.target.value) || 0 }))} />
              </SField>
            </div>

            <div style={S_styles.row2}>
              <SField label="Mileage">
                <SInput type="number" min="0" value={editing.mileage || 0} onChange={e => setEditing(d => ({ ...d, mileage: parseFloat(e.target.value) || 0 }))} />
              </SField>
              <SField label="Next service date">
                <SInput type="date" value={editing.nextService || ''} onChange={e => setEditing(d => ({ ...d, nextService: e.target.value || null }))} />
              </SField>
            </div>

            <SField label="Notes (internal)">
              <STextarea value={editing.notes || ''} onChange={e => setEditing(d => ({ ...d, notes: e.target.value }))} placeholder="Anything specific about this truck — equipped with dollies, has lift gate, etc." />
            </SField>

            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 12 }}>
              <button style={S_styles.btnSecondary} onClick={() => setEditing(null)}>Cancel</button>
              <button style={S_styles.btnPrimary} onClick={saveEdit}>{editing.id ? 'Save' : 'Create'}</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// =============================================================================
// MAIN SETTINGS VIEW — tab switcher
// =============================================================================

function SettingsView() {
  const [tab, setTab] = useState('company');
  const [myRole, setMyRole] = useState(null);

  useEffect(() => {
    window.loadMyProfile().then(p => setMyRole(p.role)).catch(() => setMyRole(null));
  }, []);

  const TABS = [
    { id: 'company',   label: 'Company',      icon: 'building' },
    { id: 'pricing',   label: 'Pricing',      icon: 'dollar-bill' },
    { id: 'capacity',  label: 'Capacity',     icon: 'ruler' },
    { id: 'documents', label: 'Documents',    icon: 'file-text' },
    { id: 'profile',   label: 'My Profile',   icon: 'user' },
    ...(myRole === 'owner' ? [{ id: 'team', label: 'Team', icon: 'users' }] : []),
    ...((myRole === 'owner' || myRole === 'staff') ? [{ id: 'crew', label: 'Crew Members', icon: 'crew' }] : []),
    ...((myRole === 'owner' || myRole === 'staff') ? [{ id: 'trucks', label: 'Trucks', icon: 'truck' }] : []),
  ];

  return (
    <div style={S_styles.page}>
      <div style={S_styles.header}>
        <h1 style={S_styles.h1}>Settings</h1>
        <div style={S_styles.subtitle}>Configure how MaxAMove works — pricing, capacity, trucks, documents, your team.</div>
      </div>

      <div style={S_styles.tabsRow}>
        {TABS.map(t => (
          <button
            key={t.id}
            style={{ ...S_styles.tabBtn, ...(tab === t.id ? S_styles.tabBtnActive : {}), display: 'inline-flex', alignItems: 'center', gap: 6 }}
            onClick={() => setTab(t.id)}
          >
            <Icon name={t.icon} size={14}/>{t.label}
          </button>
        ))}
      </div>

      <div style={{ flex: 1, minHeight: 0 }}>
        {tab === 'company'   && <CompanySection />}
        {tab === 'pricing'   && <PricingSection />}
        {tab === 'capacity'  && <CapacitySection />}
        {tab === 'documents' && <DocumentsSection />}
        {tab === 'profile'   && <MyProfileSection />}
        {tab === 'team'      && <TeamSection myRole={myRole} />}
        {tab === 'crew'      && <CrewSection myRole={myRole} />}
        {tab === 'trucks'    && <TrucksSection myRole={myRole} />}
      </div>
    </div>
  );
}

window.SettingsView = SettingsView;
