
// ── Admin Dashboard ───────────────────────────────────────────────────────────
const AdminPricingField = ({ id, label, keyName, pricing, setPricing, prefix = '$', suffix = '' }) => (
  <div style={{ marginBottom: '16px' }}>
    <label htmlFor={id} style={{ display: 'block', fontFamily: 'Inter, sans-serif', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>
      {label}
    </label>
    <div style={{ display: 'flex', alignItems: 'center', border: '1.5px solid #E2E8F0', borderRadius: '8px', overflow: 'hidden', background: '#fff' }}>
      {prefix && <span style={{ padding: '12px 12px 12px 14px', fontFamily: 'Inter, sans-serif', fontSize: '15px', fontWeight: '600', color: '#9AAAB8', background: '#F9FAFB', borderRight: '1px solid #E2E8F0' }}>{prefix}</span>}
      <input
        id={id}
        type="number"
        step="0.01"
        value={pricing?.[keyName] || ''}
        onChange={e => setPricing(p => ({ ...p, [keyName]: e.target.value }))}
        style={{ flex: 1, border: 'none', outline: 'none', padding: '12px 14px', fontFamily: 'Inter, sans-serif', fontSize: '15px', fontWeight: '600', color: '#1B2A4A', background: '#fff' }}
      />
      {suffix && <span style={{ padding: '12px 14px 12px 4px', fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#9AAAB8' }}>{suffix}</span>}
    </div>
  </div>
);

const normalizeClientEmail = (value) => String(value || '').trim().toLowerCase();

const findClientProfileByEmail = (profiles, email) => {
  const normalized = normalizeClientEmail(email);
  return profiles.find((profile) => !profile.is_admin && normalizeClientEmail(profile.email) === normalized) || null;
};

const buildClientGroups = (profiles, quotes, rentals, clientContacts) => {
  const groups = new Map();
  const profileById = new Map(profiles.map((profile) => [profile.id, profile]));
  const contactByEmail = new Map((clientContacts || []).map((contact) => [normalizeClientEmail(contact.email), contact]));
  const ensureGroup = (email) => {
    const normalized = normalizeClientEmail(email);
    if (!normalized) return null;
    if (!groups.has(normalized)) {
      groups.set(normalized, {
        email: normalized,
        names: new Set(),
        phones: new Set(),
        quoteCount: 0,
        rentalCount: 0,
        quotes: [],
        rentals: [],
        linkedProfile: null,
        contactRecord: contactByEmail.get(normalized) || null,
        lastActivity: null,
      });
    }
    return groups.get(normalized);
  };
  const pushActivity = (group, value) => {
    if (!value) return;
    const stamp = new Date(value).getTime();
    if (!Number.isFinite(stamp)) return;
    if (!group.lastActivity || stamp > group.lastActivity) group.lastActivity = stamp;
  };

  profiles.filter((profile) => !profile.is_admin).forEach((profile) => {
    const group = ensureGroup(profile.email);
    if (!group) return;
    if (profile.full_name) group.names.add(profile.full_name);
    if (profile.phone) group.phones.add(profile.phone);
    group.linkedProfile = profile;
    pushActivity(group, profile.created_at);
  });

  quotes.forEach((quote) => {
    const group = ensureGroup(quote.email);
    if (!group) return;
    if (quote.name) group.names.add(quote.name);
    if (quote.phone) group.phones.add(quote.phone);
    group.quoteCount += 1;
    group.quotes.push(quote);
    pushActivity(group, quote.created_at);
  });

  rentals.forEach((rental) => {
    const profile = rental.user_id ? profileById.get(rental.user_id) : null;
    const group = ensureGroup(rental.customer_email || profile?.email);
    if (!group) return;
    if (rental.customer_name) group.names.add(rental.customer_name);
    if (profile?.phone) group.phones.add(profile.phone);
    group.rentalCount += 1;
    group.rentals.push(rental);
    if (!group.linkedProfile && profile && !profile.is_admin) group.linkedProfile = profile;
    pushActivity(group, rental.created_at || rental.start_date);
  });

  return Array.from(groups.values())
    .map((group) => ({
      ...group,
      name: group.contactRecord?.full_name || Array.from(group.names)[0] || (group.linkedProfile?.full_name || '—'),
      phone: group.contactRecord?.phone || Array.from(group.phones)[0] || (group.linkedProfile?.phone || ''),
      company: group.contactRecord?.company || '',
      privateNotes: group.contactRecord?.private_notes || '',
      currentSales: group.quotes.filter((quote) => quote.interest === 'sale' && !['completed', 'cancelled'].includes(String(quote.status || '').toLowerCase())),
      pastSales: group.quotes.filter((quote) => quote.interest === 'sale' && String(quote.status || '').toLowerCase() === 'completed'),
    }))
    .sort((a, b) => (b.lastActivity || 0) - (a.lastActivity || 0));
};

const AdminDashboard = ({ user, onSignOut }) => {
  const [activeTab, setActiveTab] = React.useState('pricing');
  const [pricing, setPricing] = React.useState(null);
  const [quotes, setQuotes] = React.useState([]);
  const [rentals, setRentals] = React.useState([]);
  const [profiles, setProfiles] = React.useState([]);
  const [clientContacts, setClientContacts] = React.useState([]);
  const [inventory, setInventory] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [saving, setSaving] = React.useState(false);
  const [saveMsg, setSaveMsg] = React.useState('');
  const [editQuote, setEditQuote] = React.useState(null);
  const [editRental, setEditRental] = React.useState(null);
  const [viewClient, setViewClient] = React.useState(null);
  const [showNewQuote, setShowNewQuote] = React.useState(false);
  const [showNewRental, setShowNewRental] = React.useState(false);

  // Load all data
  React.useEffect(() => {
    (async () => {
      setLoading(true);
      if (SUPABASE_CONFIGURED) {
        const [p, q, r, pr, cc, inv] = await Promise.all([
          supa.getPricing(), supa.getQuotes(null, true),
          supa.getRentals(null, true), supa.getAllProfiles(),
          supa.getClientContacts(),
          supa.getInventory(),
        ]);
        setPricing(p || MOCK_DATA.pricing);
        setQuotes(Array.isArray(q) ? q : MOCK_DATA.quotes);
        setRentals(Array.isArray(r) ? r : MOCK_DATA.rentals);
        setProfiles(Array.isArray(pr) ? pr : MOCK_DATA.profiles);
        setClientContacts(Array.isArray(cc) ? cc : MOCK_DATA.client_contacts);
        setInventory(Array.isArray(inv) ? inv : MOCK_DATA.inventory);
      } else {
        await new Promise(r => setTimeout(r, 400));
        setPricing({ ...MOCK_DATA.pricing });
        setQuotes([...MOCK_DATA.quotes]);
        setRentals([...MOCK_DATA.rentals]);
        setProfiles([...MOCK_DATA.profiles]);
        setClientContacts([...(MOCK_DATA.client_contacts || [])]);
        setInventory([...MOCK_DATA.inventory]);
      }
      setLoading(false);
    })();
  }, []);

  const savePricing = async () => {
    setSaving(true);
    if (SUPABASE_CONFIGURED) await supa.savePricing(pricing);
    // Also update the in-memory PRICING object used by EstimatorPage
    if (window.PRICING) {
      window.PRICING.sale['20-new']  = Number(pricing.sale_20_new);
      window.PRICING.sale['20-used'] = Number(pricing.sale_20_used);
      window.PRICING.sale['40-new']  = Number(pricing.sale_40_new);
      window.PRICING.sale['40-used'] = Number(pricing.sale_40_used);
      window.PRICING.rental['20-new']  = Number(pricing.rent_20_new);
      window.PRICING.rental['20-used'] = Number(pricing.rent_20_used);
      window.PRICING.rental['40-new']  = Number(pricing.rent_40_new);
      window.PRICING.rental['40-used'] = Number(pricing.rent_40_used);
      window.PRICING.delivery.flatFee   = Number(pricing.delivery_flat);
      window.PRICING.delivery.includedMiles = Number(pricing.delivery_included_miles);
      window.PRICING.delivery.perMile   = Number(pricing.delivery_per_mile);
      window.PRICING.delivery.maxRadius = Number(pricing.delivery_max_radius);
      window.PRICING.delivery.hubZip    = pricing.delivery_hub_zip;
      window.PRICING.taxRate            = normalizeTaxRateDecimal(pricing.tax_rate);
      window.PRICING.buyoutCreditRate   = Number(pricing.buyout_credit_rate);
    }
    await new Promise(r => setTimeout(r, 300));
    setSaving(false);
    setSaveMsg('✓ Saved and applied to estimator');
    setTimeout(() => setSaveMsg(''), 3000);
  };

  const StatusBadge = ({ status }) => {
    const colors = { pending: ['#FFF8E1','#856404'], quoted: ['#EBF8FF','#2B6CB0'], active: ['#F0FFF4','#276749'], completed: ['#F7FAFC','#4A5568'], cancelled: ['#FFF5F5','#C53030'] };
    const [bg, color] = colors[status] || ['#F7FAFC','#4A5568'];
    return <span style={{ background: bg, color, fontFamily: 'Inter, sans-serif', fontSize: '11px', fontWeight: '700', padding: '3px 10px', borderRadius: '100px', letterSpacing: '0.04em', textTransform: 'uppercase' }}>{status}</span>;
  };

  const TabBtn = ({ id, label, count }) => (
    <button onClick={() => setActiveTab(id)} style={{
      padding: '10px 20px', border: 'none', cursor: 'pointer', borderRadius: '8px',
      fontFamily: 'Inter, sans-serif', fontSize: '13px', fontWeight: '600',
      background: activeTab === id ? '#1B2A4A' : 'transparent',
      color: activeTab === id ? '#fff' : '#6B7E96',
      display: 'flex', alignItems: 'center', gap: '8px', transition: 'all 0.2s',
    }}>
      {label}
      {count !== undefined && (
        <span style={{ background: activeTab === id ? 'rgba(74,159,212,0.4)' : '#E2E8F0', color: activeTab === id ? '#fff' : '#6B7E96', borderRadius: '100px', padding: '1px 8px', fontSize: '11px', fontWeight: '700' }}>
          {count}
        </span>
      )}
    </button>
  );

  if (loading) return (
    <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#F4F6F8' }}>
      <div style={{ textAlign: 'center' }}>
        <div style={{ width: '40px', height: '40px', border: '3px solid #E2E8F0', borderTopColor: '#4A9FD4', borderRadius: '50%', animation: 'spin 0.8s linear infinite', margin: '0 auto 16px' }} />
        <p style={{ fontFamily: 'Inter, sans-serif', color: '#9AAAB8', fontSize: '14px' }}>Loading dashboard…</p>
      </div>
      <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
    </div>
  );

  const clientGroups = buildClientGroups(profiles, quotes, rentals, clientContacts);

  return (
    <div style={{ minHeight: '100vh', background: '#F4F6F8', fontFamily: 'Inter, sans-serif' }}>
      {/* Top bar */}
      <div style={{ background: '#1B2A4A', padding: '0 32px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', height: '64px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
          <img src="uploads/logo-7179fe62.png" alt="Sea Steel Storage" style={{ height: '36px', objectFit: 'contain' }} />
          <div style={{ width: '1px', height: '28px', background: 'rgba(255,255,255,0.15)' }} />
          <span style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '18px', fontWeight: '700', color: '#4A9FD4', letterSpacing: '0.04em' }}>ADMIN</span>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
          <span style={{ fontSize: '13px', color: 'rgba(255,255,255,0.5)' }}>{user.email}</span>
          <button onClick={onSignOut} style={{ background: 'rgba(255,255,255,0.08)', border: '1px solid rgba(255,255,255,0.15)', color: 'rgba(255,255,255,0.7)', borderRadius: '6px', padding: '7px 16px', cursor: 'pointer', fontFamily: 'Inter, sans-serif', fontSize: '13px', fontWeight: '600', transition: 'all 0.2s' }}
            onMouseEnter={e => e.target.style.background = 'rgba(255,255,255,0.15)'}
            onMouseLeave={e => e.target.style.background = 'rgba(255,255,255,0.08)'}>
            Sign Out
          </button>
        </div>
      </div>

      <div style={{ maxWidth: '1200px', margin: '0 auto', padding: '32px' }}>
        {/* Stats row */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '16px', marginBottom: '28px' }}>
          {[
            { label: 'Total Quotes', value: quotes.length, color: '#4A9FD4' },
            { label: 'Active Rentals', value: rentals.filter(r => r.status === 'active').length, color: '#38A169' },
            { label: 'Pending Quotes', value: quotes.filter(q => q.status === 'pending').length, color: '#D69E2E' },
            { label: 'Total Clients', value: clientGroups.length, color: '#805AD5' },
          ].map(s => (
            <div key={s.label} style={{ background: '#fff', borderRadius: '10px', padding: '20px 24px', border: '1px solid #E8EDF2' }}>
              <div style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '36px', fontWeight: '800', color: s.color }}>{s.value}</div>
              <div style={{ fontSize: '13px', color: '#6B7E96', fontWeight: '600', marginTop: '2px' }}>{s.label}</div>
            </div>
          ))}
        </div>

        {/* Tab nav */}
        <div style={{ display: 'flex', gap: '4px', background: '#fff', padding: '6px', borderRadius: '10px', marginBottom: '24px', border: '1px solid #E8EDF2' }}>
          <TabBtn id="pricing" label="💰 Pricing" />
          <TabBtn id="quotes" label="📋 Quotes" count={quotes.length} />
          <TabBtn id="rentals" label="📦 Rentals" count={rentals.length} />
          <TabBtn id="inventory" label="🏗 Inventory" count={inventory.length} />
          <TabBtn id="clients" label="👤 Clients" count={clientGroups.length} />
        </div>

        {/* ── PRICING TAB ── */}
        {activeTab === 'pricing' && pricing && (
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '24px' }}>
            {/* Sale prices */}
            <div style={{ background: '#fff', borderRadius: '12px', padding: '28px', border: '1px solid #E8EDF2' }}>
              <h3 style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '20px', fontWeight: '700', color: '#1B2A4A', margin: '0 0 20px 0' }}>Container Sale Prices</h3>
              <AdminPricingField id="sale_20_new" label="20' New" keyName="sale_20_new" pricing={pricing} setPricing={setPricing} />
              <AdminPricingField id="sale_20_used" label="20' Used" keyName="sale_20_used" pricing={pricing} setPricing={setPricing} />
              <AdminPricingField id="sale_40_new" label="40' New HC" keyName="sale_40_new" pricing={pricing} setPricing={setPricing} />
              <AdminPricingField id="sale_40_used" label="40' Used" keyName="sale_40_used" pricing={pricing} setPricing={setPricing} />
            </div>

            {/* Rental rates */}
            <div style={{ background: '#fff', borderRadius: '12px', padding: '28px', border: '1px solid #E8EDF2' }}>
              <h3 style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '20px', fontWeight: '700', color: '#1B2A4A', margin: '0 0 20px 0' }}>Monthly Rental Rates</h3>
              <AdminPricingField id="rent_20_new" label="20' New / month" keyName="rent_20_new" pricing={pricing} setPricing={setPricing} />
              <AdminPricingField id="rent_20_used" label="20' Used / month" keyName="rent_20_used" pricing={pricing} setPricing={setPricing} />
              <AdminPricingField id="rent_40_new" label="40' New / month" keyName="rent_40_new" pricing={pricing} setPricing={setPricing} />
              <AdminPricingField id="rent_40_used" label="40' Used / month" keyName="rent_40_used" pricing={pricing} setPricing={setPricing} />
            </div>

            {/* Delivery */}
            <div style={{ background: '#fff', borderRadius: '12px', padding: '28px', border: '1px solid #E8EDF2' }}>
              <h3 style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '20px', fontWeight: '700', color: '#1B2A4A', margin: '0 0 20px 0' }}>Delivery Settings</h3>
              <AdminPricingField id="delivery_flat" label="Base fee" keyName="delivery_flat" pricing={pricing} setPricing={setPricing} />
              <AdminPricingField id="delivery_included_miles" label="Miles included in base fee" keyName="delivery_included_miles" pricing={pricing} setPricing={setPricing} prefix="" suffix="miles" />
              <AdminPricingField id="delivery_per_mile" label="Additional rate per mile" keyName="delivery_per_mile" pricing={pricing} setPricing={setPricing} />
              <AdminPricingField id="delivery_max_radius" label="Max radius (miles)" keyName="delivery_max_radius" pricing={pricing} setPricing={setPricing} prefix="mi" />
              <div style={{ marginBottom: '16px' }}>
                <label style={{ display: 'block', fontFamily: 'Inter, sans-serif', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Hub ZIP Code</label>
                <input type="text" value={pricing.delivery_hub_zip || ''} onChange={e => setPricing(p => ({ ...p, delivery_hub_zip: e.target.value }))}
                  style={{ width: '100%', boxSizing: 'border-box', border: '1.5px solid #E2E8F0', borderRadius: '8px', padding: '12px 14px', fontFamily: 'Inter, sans-serif', fontSize: '15px', fontWeight: '600', color: '#1B2A4A', outline: 'none' }}
                  onFocus={e => e.target.style.borderColor = '#4A9FD4'}
                  onBlur={e => e.target.style.borderColor = '#E2E8F0'}
                />
              </div>
              <div style={{ marginBottom: '16px' }}>
                <label style={{ display: 'block', fontFamily: 'Inter, sans-serif', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Google Routing Preference</label>
                <select
                  value={pricing.google_routes_routing_preference || 'TRAFFIC_UNAWARE'}
                  onChange={e => setPricing(p => ({ ...p, google_routes_routing_preference: e.target.value }))}
                  style={{ width: '100%', boxSizing: 'border-box', border: '1.5px solid #E2E8F0', borderRadius: '8px', padding: '12px 14px', fontFamily: 'Inter, sans-serif', fontSize: '15px', fontWeight: '600', color: '#1B2A4A', outline: 'none', cursor: 'pointer', background: '#fff' }}
                  onFocus={e => e.target.style.borderColor = '#4A9FD4'}
                  onBlur={e => e.target.style.borderColor = '#E2E8F0'}
                >
                  <option value="TRAFFIC_UNAWARE">Traffic Unaware</option>
                  <option value="TRAFFIC_AWARE">Traffic Aware</option>
                  <option value="TRAFFIC_AWARE_OPTIMAL">Traffic Aware Optimal</option>
                </select>
                <p style={{ fontFamily: 'Inter, sans-serif', fontSize: '12px', color: '#9AAAB8', marginTop: '4px', lineHeight: '1.5' }}>
                  Use `TRAFFIC_UNAWARE` for delivery pricing by route miles. Traffic-aware modes are better for ETA accuracy.
                </p>
              </div>
              <div style={{ marginTop: '24px', padding: '16px', background: '#F4F6F8', borderRadius: '8px' }}>
                <p style={{ fontSize: '13px', color: '#6B7E96', lineHeight: '1.6', margin: 0 }}>
                  Delivery estimate formula:
                  <strong style={{ color: '#1B2A4A' }}> base fee</strong> covers the first
                  <strong style={{ color: '#1B2A4A' }}> included miles</strong>, then the
                  <strong style={{ color: '#1B2A4A' }}> additional per-mile rate</strong> applies after that. Delivery is taxable.
                </p>
              </div>
            </div>

            {/* Tax & Buyout */}
            <div style={{ background: '#fff', borderRadius: '12px', padding: '28px', border: '1px solid #E8EDF2' }}>
              <h3 style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '20px', fontWeight: '700', color: '#1B2A4A', margin: '0 0 20px 0' }}>Tax & Buyout</h3>
              <AdminPricingField id="tax_rate" label="Sales tax rate (decimal)" keyName="tax_rate" pricing={pricing} setPricing={setPricing} prefix="" suffix="e.g. 0.10 = 10%" />
              <AdminPricingField id="buyout_credit_rate" label="Buyout credit rate (decimal)" keyName="buyout_credit_rate" pricing={pricing} setPricing={setPricing} prefix="" suffix="e.g. 0.50 = 50%" />
              <div style={{ marginTop: '24px', padding: '16px', background: '#F4F6F8', borderRadius: '8px' }}>
                <p style={{ fontSize: '13px', color: '#6B7E96', lineHeight: '1.6', margin: 0 }}>
                  These values drive the <strong style={{ color: '#1B2A4A' }}>Price Estimator</strong> in real time. Changes are applied immediately to all estimates.
                </p>
              </div>
            </div>

            {/* Save button */}
            <div style={{ gridColumn: '1 / -1', display: 'flex', alignItems: 'center', gap: '16px' }}>
              <button onClick={savePricing} disabled={saving} style={{
                background: saving ? '#9AAAB8' : '#1B2A4A', color: '#fff', border: 'none', cursor: saving ? 'not-allowed' : 'pointer',
                fontFamily: 'Inter, sans-serif', fontSize: '15px', fontWeight: '700',
                padding: '14px 36px', borderRadius: '8px', transition: 'all 0.2s',
              }}
              onMouseEnter={e => { if (!saving) e.target.style.background = '#4A9FD4'; }}
              onMouseLeave={e => { if (!saving) e.target.style.background = '#1B2A4A'; }}
              >
                {saving ? 'Saving…' : '💾 Save Pricing'}
              </button>
              {saveMsg && <span style={{ fontFamily: 'Inter, sans-serif', fontSize: '14px', color: '#38A169', fontWeight: '600' }}>{saveMsg}</span>}
            </div>
          </div>
        )}

        {/* ── QUOTES TAB ── */}
        {activeTab === 'quotes' && (
          <div style={{ background: '#fff', borderRadius: '12px', border: '1px solid #E8EDF2', overflow: 'hidden' }}>
            <div style={{ padding: '20px 24px', borderBottom: '1px solid #EEF2F7', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <h3 style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '20px', fontWeight: '700', color: '#1B2A4A', margin: 0 }}>All Quotes</h3>
              <button onClick={() => setShowNewQuote(true)} style={{ background: '#1B2A4A', color: '#fff', border: 'none', borderRadius: '8px', padding: '11px 18px', cursor: 'pointer', fontFamily: 'Inter, sans-serif', fontSize: '13px', fontWeight: '700' }}>
                + New Quote
              </button>
            </div>
            <div style={{ overflowX: 'auto' }}>
              <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                <thead>
                  <tr style={{ background: '#F9FAFB' }}>
                    {['Date', 'Name', 'Email', 'ZIP', 'Interest', 'Size', 'Condition', 'Status', 'Actions'].map(h => (
                      <th key={h} style={{ padding: '12px 16px', fontFamily: 'Inter, sans-serif', fontSize: '11px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', textAlign: 'left', borderBottom: '1px solid #EEF2F7', whiteSpace: 'nowrap' }}>{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {quotes.map((q, i) => (
                    <tr key={q.id} style={{ background: i % 2 === 0 ? '#fff' : '#FAFBFC' }}>
                      <td style={{ padding: '14px 16px', fontSize: '13px', color: '#6B7E96', whiteSpace: 'nowrap' }}>{new Date(q.created_at).toLocaleDateString()}</td>
                      <td style={{ padding: '14px 16px', fontSize: '14px', fontWeight: '600', color: '#1B2A4A' }}>{q.name}</td>
                      <td style={{ padding: '14px 16px', fontSize: '13px', color: '#4A5568' }}>{q.email}</td>
                      <td style={{ padding: '14px 16px', fontSize: '13px', color: '#4A5568' }}>{q.zip}</td>
                      <td style={{ padding: '14px 16px', fontSize: '13px', color: '#4A5568', textTransform: 'capitalize' }}>{q.interest}</td>
                      <td style={{ padding: '14px 16px', fontSize: '13px', color: '#4A5568' }}>{q.size}</td>
                      <td style={{ padding: '14px 16px', fontSize: '13px', color: '#4A5568' }}>{q.condition}</td>
                      <td style={{ padding: '14px 16px' }}><StatusBadge status={q.status || 'pending'} /></td>
                      <td style={{ padding: '14px 16px' }}>
                        <button onClick={() => setEditQuote(q)} style={{ background: 'none', border: '1px solid #E2E8F0', borderRadius: '6px', padding: '5px 12px', cursor: 'pointer', fontFamily: 'Inter, sans-serif', fontSize: '12px', fontWeight: '600', color: '#4A9FD4', transition: 'all 0.2s' }}>Edit</button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
              {quotes.length === 0 && <p style={{ textAlign: 'center', padding: '40px', color: '#9AAAB8', fontFamily: 'Inter, sans-serif' }}>No quotes yet.</p>}
            </div>
          </div>
        )}

        {/* ── RENTALS TAB ── */}
        {activeTab === 'rentals' && (
          <div>
            <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: '16px' }}>
              <button onClick={() => setShowNewRental(true)} style={{ background: '#1B2A4A', color: '#fff', border: 'none', borderRadius: '8px', padding: '11px 24px', cursor: 'pointer', fontFamily: 'Inter, sans-serif', fontSize: '14px', fontWeight: '700', transition: 'background 0.2s' }}
                onMouseEnter={e => e.target.style.background = '#4A9FD4'}
                onMouseLeave={e => e.target.style.background = '#1B2A4A'}>
                + Add Rental
              </button>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
              {rentals.map(r => (
                <RentalCard key={r.id} rental={r} isAdmin onEdit={() => setEditRental(r)} />
              ))}
              {rentals.length === 0 && (
                <div style={{ background: '#fff', borderRadius: '12px', border: '1px solid #E8EDF2', padding: '48px', textAlign: 'center', color: '#9AAAB8', fontFamily: 'Inter, sans-serif' }}>
                  No rentals yet. Click "+ Add Rental" to create one.
                </div>
              )}
            </div>
          </div>
        )}

        {/* ── INVENTORY TAB ── */}
        {activeTab === 'inventory' && (
          <AdminInventoryTab
            inventory={inventory}
            setInventory={setInventory}
            pricing={pricing}
            setPricing={setPricing}
            onSavePricing={savePricing}
          />
        )}

        {/* ── CLIENTS TAB ── */}
        {activeTab === 'clients' && (
          <div style={{ background: '#fff', borderRadius: '12px', border: '1px solid #E8EDF2', overflow: 'hidden' }}>
            <div style={{ padding: '20px 24px', borderBottom: '1px solid #EEF2F7' }}>
              <h3 style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '20px', fontWeight: '700', color: '#1B2A4A', margin: 0 }}>Clients Grouped by Email</h3>
            </div>
            <div style={{ overflowX: 'auto' }}>
              <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                <thead>
                  <tr style={{ background: '#F9FAFB' }}>
                    {['Name', 'Email', 'Phone', 'Quotes', 'Rentals', 'Portal', 'Last Activity'].map(h => (
                      <th key={h} style={{ padding: '12px 16px', fontFamily: 'Inter, sans-serif', fontSize: '11px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', textAlign: 'left', borderBottom: '1px solid #EEF2F7' }}>{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {clientGroups.map((client, i) => (
                    <tr key={client.email} style={{ background: i % 2 === 0 ? '#fff' : '#FAFBFC', cursor: 'pointer' }} onClick={() => setViewClient(client)}>
                      <td style={{ padding: '14px 16px', fontSize: '14px', fontWeight: '600', color: '#1B2A4A' }}>{client.name}</td>
                      <td style={{ padding: '14px 16px', fontSize: '13px', color: '#4A5568' }}>{client.email}</td>
                      <td style={{ padding: '14px 16px', fontSize: '13px', color: '#4A5568' }}>{client.phone || '—'}</td>
                      <td style={{ padding: '14px 16px' }}>
                        <span style={{ fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#1B2A4A', fontWeight: '700' }}>{client.quoteCount}</span>
                      </td>
                      <td style={{ padding: '14px 16px' }}>
                        <span style={{ fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#1B2A4A', fontWeight: '700' }}>{client.rentalCount}</span>
                      </td>
                      <td style={{ padding: '14px 16px' }}>
                        <span style={{ background: client.linkedProfile ? '#F0FFF4' : '#FFF8E1', color: client.linkedProfile ? '#276749' : '#856404', fontFamily: 'Inter, sans-serif', fontSize: '11px', fontWeight: '700', padding: '3px 10px', borderRadius: '100px' }}>
                          {client.linkedProfile ? 'Linked' : 'No Account'}
                        </span>
                      </td>
                      <td style={{ padding: '14px 16px', fontSize: '13px', color: '#6B7E96' }}>{client.lastActivity ? new Date(client.lastActivity).toLocaleDateString() : '—'}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}
      </div>

      {viewClient && (
        <Modal title="Client CRM Card" maxWidth="1120px" onClose={() => setViewClient(null)}>
          <ClientCRMCard
            client={viewClient}
            onSave={async (data) => {
              const payload = {
                email: viewClient.email,
                full_name: data.full_name,
                phone: data.phone,
                company: data.company,
                private_notes: data.private_notes,
                updated_at: new Date().toISOString(),
              };

              if (SUPABASE_CONFIGURED) {
                await supa.saveClientContact(payload);
              }

              setClientContacts((contacts) => {
                const existing = contacts.find((contact) => normalizeClientEmail(contact.email) === viewClient.email);
                if (existing) {
                  return contacts.map((contact) => normalizeClientEmail(contact.email) === viewClient.email ? { ...contact, ...payload } : contact);
                }
                return [{ ...payload, created_at: new Date().toISOString() }, ...contacts];
              });
              setViewClient((current) => current ? { ...current, name: data.full_name || current.name, phone: data.phone || current.phone, company: data.company || '', privateNotes: data.private_notes || '' } : current);
            }}
            onEditQuote={(quote) => {
              setViewClient(null);
              setEditQuote(quote);
            }}
            onEditRental={(rental) => {
              setViewClient(null);
              setEditRental(rental);
            }}
          />
        </Modal>
      )}

      {/* ── Edit Quote Modal ── */}
      {editQuote && (
        <Modal title="Edit Quote" maxWidth="1040px" onClose={() => setEditQuote(null)}>
          <QuoteEditForm quote={editQuote} pricing={pricing} onSave={async (data) => {
            if (SUPABASE_CONFIGURED) await supa.updateQuote(editQuote.id, data);
            setQuotes(qs => qs.map(q => q.id === editQuote.id ? { ...q, ...data } : q));
            setEditQuote(null);
          }} onDraftSave={async (data) => {
            if (SUPABASE_CONFIGURED) await supa.updateQuote(editQuote.id, data);
            setQuotes(qs => qs.map(q => q.id === editQuote.id ? { ...q, ...data } : q));
            setEditQuote(q => (q && q.id === editQuote.id ? { ...q, ...data } : q));
          }} onSent={(updatedQuote) => {
            setQuotes(qs => qs.map(q => q.id === updatedQuote.id ? { ...q, ...updatedQuote } : q));
            setEditQuote(null);
          }} />
        </Modal>
      )}

      {/* ── New Quote Modal ── */}
      {showNewQuote && (
        <Modal title="Create Quote" onClose={() => setShowNewQuote(false)}>
          <ManualQuoteCreateForm
            profiles={profiles}
            onCreate={async (data) => {
              const matchedProfile = findClientProfileByEmail(profiles, data.email);
              const payload = {
                ...data,
                email: normalizeClientEmail(data.email),
                user_id: matchedProfile?.id || null,
              };

              if (SUPABASE_CONFIGURED) {
                const rows = await supa.saveQuote(payload);
                const createdQuote = Array.isArray(rows) ? rows[0] : rows;
                if (createdQuote) {
                  setQuotes((qs) => [createdQuote, ...qs]);
                  setShowNewQuote(false);
                  setEditQuote(createdQuote);
                  return;
                }
              }

              const createdQuote = { ...payload, id: String(Date.now()), created_at: new Date().toISOString() };
              setQuotes((qs) => [createdQuote, ...qs]);
              setShowNewQuote(false);
              setEditQuote(createdQuote);
            }}
          />
        </Modal>
      )}

      {/* ── Edit/Add Rental Modal ── */}
      {(editRental || showNewRental) && (
        <Modal title={editRental ? 'Edit Rental' : 'Add New Rental'} onClose={() => { setEditRental(null); setShowNewRental(false); }}>
          <RentalEditForm
            rental={editRental}
            profiles={profiles}
            onSave={async (data) => {
              if (editRental) {
                if (SUPABASE_CONFIGURED) {
                  const rows = await supa.updateRental(editRental.id, data);
                  const updatedRental = Array.isArray(rows) ? rows[0] : rows;
                  setRentals(rs => rs.map(r => r.id === editRental.id ? { ...r, ...(updatedRental || data) } : r));
                } else {
                  setRentals(rs => rs.map(r => r.id === editRental.id ? { ...r, ...data } : r));
                }
              } else {
                if (SUPABASE_CONFIGURED) {
                  const rows = await supa.saveRental(data);
                  const createdRental = Array.isArray(rows) ? rows[0] : rows;
                  setRentals(rs => [createdRental || { ...data, id: String(Date.now()) }, ...rs]);
                } else {
                  const newR = { ...data, id: String(Date.now()) };
                  setRentals(rs => [newR, ...rs]);
                }
              }
              setEditRental(null); setShowNewRental(false);
            }}
          />
        </Modal>
      )}
    </div>
  );
};

// ── Shared Modal wrapper ──────────────────────────────────────────────────────
const Modal = ({ title, children, onClose, maxWidth = '560px' }) => (
  <div style={{
    position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', zIndex: 9000,
    display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '24px',
  }} onClick={e => e.target === e.currentTarget && onClose()}>
    <div style={{ background: '#fff', borderRadius: '16px', width: '100%', maxWidth, maxHeight: '90vh', overflowY: 'auto', boxShadow: '0 24px 64px rgba(0,0,0,0.3)' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '20px 24px', borderBottom: '1px solid #EEF2F7' }}>
        <h3 style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '22px', fontWeight: '700', color: '#1B2A4A', margin: 0 }}>{title}</h3>
        <button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: '20px', color: '#9AAAB8', padding: '4px 8px', borderRadius: '6px' }}>✕</button>
      </div>
      <div style={{ padding: '24px' }}>{children}</div>
    </div>
  </div>
);

const createQuoteBuilderItem = (overrides = {}) => ({
  id: overrides.id || `item_${Date.now()}_${Math.random().toString(36).slice(2, 7)}`,
  label: overrides.label || '',
  description: overrides.description || '',
  quantity: overrides.quantity ?? 1,
  unitPrice: overrides.unitPrice ?? '',
});

const toMoneyNumber = (value) => {
  const num = Number(value);
  return Number.isFinite(num) ? num : 0;
};

const formatMoney = (value) => `$${toMoneyNumber(value).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
const normalizeTaxRateDecimal = (value) => {
  const numeric = Number(value);
  if (!Number.isFinite(numeric) || numeric < 0) return 0;
  return numeric > 1 ? numeric / 100 : numeric;
};
const getDeliveryIncludedMiles = (pricing) => Math.max(0, Number(pricing?.delivery_included_miles ?? 45) || 45);
const computeDeliveryEstimateFromMiles = (miles, pricing, quoteKind = 'sale') => {
  if (typeof miles !== 'number') return null;
  const maxRadius = Number(pricing?.delivery_max_radius || 150);
  if (miles > maxRadius) return 'out-of-range';
  const baseFee = Number(pricing?.delivery_flat || 250);
  const additionalRate = Number(pricing?.delivery_per_mile || 2.5);
  const additionalMiles = Math.max(0, miles - getDeliveryIncludedMiles(pricing));
  const oneWay = baseFee + (additionalMiles * additionalRate);
  const trips = quoteKind === 'rental' ? 2 : 1;
  return Math.round((oneWay * trips) * 100) / 100;
};
const formatTaxRatePercent = (value) => {
  const percent = normalizeTaxRateDecimal(value) * 100;
  return `${percent.toFixed(percent % 1 === 0 ? 0 : 2)}%`;
};

const getQuoteDraftStorageKey = (quoteId) => `sss_quote_builder_${quoteId}`;

const formatQuoteSizeLabel = (value) => {
  const text = String(value || '').trim();
  if (!text) return '';
  return /^\d+$/.test(text) ? `${text}'` : text;
};

const buildDefaultQuoteDraft = (quote, pricing) => ({
  subject: `Your Sea Steel Storage Quote`,
  intro: `Thanks for reaching out. Based on your request, we've put together the quote below.`,
  quoteTitle: quote.interest === 'rental' ? 'Rental Quote' : 'Container Quote',
  quoteKind: quote.interest === 'rental' ? 'rental' : 'sale',
  validDays: 7,
  deliveryFee: '',
  discount: '',
  taxRate: String(normalizeTaxRateDecimal(pricing?.tax_rate || 0)),
  rentalTermMonths: 6,
  rentalMonthlyRate: quote.interest === 'rental' ? (quote.quoted_price || '') : '',
  rentalDeposit: '',
  footer: 'Reply to this email or call us if you want us to revise the quote, add delivery details, or reserve inventory.',
  terms: 'Quote subject to inventory availability. Delivery pricing assumes standard site access. Taxes and permit requirements may vary by jurisdiction.',
  lineItems: [
    createQuoteBuilderItem({
      label: [formatQuoteSizeLabel(quote.size), quote.condition || '', quote.interest ? `${quote.interest} container` : 'container quote']
        .filter(Boolean)
        .join(' ')
        .replace(/\s+/g, ' ')
        .trim() || 'Container quote',
      description: quote.message || '',
      quantity: 1,
      unitPrice: quote.quoted_price || '',
    }),
  ],
});

const computeQuoteBuilderTotals = (draft) => {
  const lineItems = Array.isArray(draft.lineItems)
    ? draft.lineItems
        .map((item) => ({
          ...item,
          quantity: Math.max(1, Number(item.quantity) || 1),
          unitPrice: toMoneyNumber(item.unitPrice),
        }))
        .filter((item) => item.label.trim() || item.unitPrice > 0)
    : [];

  const itemsSubtotal = lineItems.reduce((sum, item) => sum + (item.quantity * item.unitPrice), 0);
  const deliveryFee = toMoneyNumber(draft.deliveryFee);
  const discount = toMoneyNumber(draft.discount);
  const taxRate = normalizeTaxRateDecimal(draft.taxRate);
  const quoteKind = draft.quoteKind === 'rental' ? 'rental' : 'sale';

  if (quoteKind === 'rental') {
    const rentalMonthlyRate = toMoneyNumber(draft.rentalMonthlyRate);
    const rentalTermMonths = Math.max(1, Number(draft.rentalTermMonths) || 6);
    const rentalDeposit = toMoneyNumber(draft.rentalDeposit);
    const monthlyRate = rentalMonthlyRate > 0 ? rentalMonthlyRate : itemsSubtotal;
    const dueAtSigningSubtotal = Math.max(0, monthlyRate + deliveryFee + rentalDeposit - discount);
    const dueAtSigningTax = dueAtSigningSubtotal * taxRate;
    const dueAtSigningTotal = dueAtSigningSubtotal + dueAtSigningTax;
    const estimatedTermSubtotal = Math.max(0, (monthlyRate * rentalTermMonths) + deliveryFee + rentalDeposit - discount);
    const estimatedTermTax = estimatedTermSubtotal * taxRate;
    const total = estimatedTermSubtotal + estimatedTermTax;

    return {
      quoteKind,
      lineItems,
      itemsSubtotal,
      deliveryFee,
      discount,
      subtotal: estimatedTermSubtotal,
      taxRate,
      taxAmount: estimatedTermTax,
      total,
      totalLabel: 'Estimated Term Total',
      monthlyRate,
      rentalTermMonths,
      rentalDeposit,
      dueAtSigningSubtotal,
      dueAtSigningTax,
      dueAtSigningTotal,
    };
  }

  const subtotal = Math.max(0, itemsSubtotal + deliveryFee - discount);
  const taxAmount = subtotal * taxRate;
  const total = subtotal + taxAmount;

  return {
    quoteKind,
    lineItems,
    itemsSubtotal,
    deliveryFee,
    discount,
    subtotal,
    taxRate,
    taxAmount,
    total,
    totalLabel: 'Quote Total',
    monthlyRate: 0,
    rentalTermMonths: Math.max(1, Number(draft.rentalTermMonths) || 6),
    rentalDeposit: 0,
    dueAtSigningSubtotal: 0,
    dueAtSigningTax: 0,
    dueAtSigningTotal: 0,
  };
};

const ManualQuoteCreateForm = ({ profiles, onCreate }) => {
  const [form, setForm] = React.useState({
    name: '',
    email: '',
    phone: '',
    zip: '',
    interest: 'sale',
    size: '20',
    condition: 'New',
    delivery: '',
    message: '',
    status: 'pending',
  });
  const [error, setError] = React.useState('');
  const fld = { fontFamily: 'Inter, sans-serif', fontSize: '14px', fontWeight: '600', color: '#1B2A4A', border: '1.5px solid #E2E8F0', borderRadius: '8px', padding: '10px 14px', width: '100%', boxSizing: 'border-box', outline: 'none' };
  const clients = profiles.filter((profile) => !profile.is_admin && profile.email);
  const set = (key, value) => setForm((state) => ({ ...state, [key]: value }));

  const handleClientPick = (profileId) => {
    const profile = clients.find((item) => item.id === profileId);
    if (!profile) return;
    setForm((state) => ({
      ...state,
      name: profile.full_name || state.name,
      email: profile.email || state.email,
      phone: profile.phone || state.phone,
    }));
  };

  const handleCreate = async () => {
    const normalizedEmail = normalizeClientEmail(form.email);
    const normalizedZip = String(form.zip || '').replace(/\D/g, '').slice(0, 5);
    if (!form.name.trim()) { setError('Customer name is required.'); return; }
    if (!normalizedEmail || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(normalizedEmail)) { setError('A valid email is required.'); return; }
    if (normalizedZip.length !== 5) { setError('A valid 5-digit ZIP is required.'); return; }
    setError('');
    await onCreate({
      ...form,
      name: form.name.trim(),
      email: normalizedEmail,
      phone: form.phone.trim(),
      zip: normalizedZip,
      delivery: form.delivery.trim(),
      message: form.message.trim(),
    });
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '14px' }}>
      <div>
        <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Existing Client</label>
        <select value="" onChange={(e) => handleClientPick(e.target.value)} style={{ ...fld, cursor: 'pointer' }}>
          <option value="">Select existing client or enter manually</option>
          {clients.map((profile) => (
            <option key={profile.id} value={profile.id}>{profile.full_name || profile.email} · {profile.email}</option>
          ))}
        </select>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
        <div>
          <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Customer Name</label>
          <input value={form.name} onChange={(e) => set('name', e.target.value)} style={fld} placeholder="Jane Smith" />
        </div>
        <div>
          <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Email</label>
          <input type="email" value={form.email} onChange={(e) => set('email', e.target.value)} style={fld} placeholder="jane@example.com" />
        </div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
        <div>
          <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Phone</label>
          <input value={form.phone} onChange={(e) => set('phone', e.target.value)} style={fld} placeholder="(253) 555-0100" />
        </div>
        <div>
          <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>ZIP</label>
          <input value={form.zip} onChange={(e) => set('zip', e.target.value)} style={fld} placeholder="98001" />
        </div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '12px' }}>
        <div>
          <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Quote Type</label>
          <select value={form.interest} onChange={(e) => set('interest', e.target.value)} style={{ ...fld, cursor: 'pointer' }}>
            <option value="sale">Sale</option>
            <option value="rental">Rental</option>
          </select>
        </div>
        <div>
          <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Size</label>
          <select value={form.size} onChange={(e) => set('size', e.target.value)} style={{ ...fld, cursor: 'pointer' }}>
            <option value="20">20</option>
            <option value="40">40</option>
          </select>
        </div>
        <div>
          <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Condition</label>
          <select value={form.condition} onChange={(e) => set('condition', e.target.value)} style={{ ...fld, cursor: 'pointer' }}>
            <option value="New">New</option>
            <option value="Used">Used</option>
            <option value="Cargo Worthy">Cargo Worthy</option>
            <option value="Wind & Water Tight">Wind & Water Tight</option>
          </select>
        </div>
      </div>
      <div>
        <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Delivery Notes</label>
        <input value={form.delivery} onChange={(e) => set('delivery', e.target.value)} style={fld} placeholder="Site access, city, or scheduling notes" />
      </div>
      <div>
        <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Request Summary</label>
        <textarea value={form.message} onChange={(e) => set('message', e.target.value)} rows={3} style={{ ...fld, resize: 'vertical' }} placeholder="What this quote is for..." />
      </div>
      {error && <div style={{ background: '#FFF5F5', border: '1px solid #FEB2B2', borderRadius: '8px', padding: '10px 12px', fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#C53030' }}>{error}</div>}
      <button type="button" onClick={handleCreate} style={{ width: '100%', background: '#1B2A4A', color: '#fff', border: 'none', borderRadius: '8px', padding: '13px', cursor: 'pointer', fontFamily: 'Inter, sans-serif', fontSize: '15px', fontWeight: '700' }}>
        Create Quote Draft
      </button>
    </div>
  );
};

const ClientCRMCard = ({ client, onSave, onEditQuote, onEditRental }) => {
  const [form, setForm] = React.useState({
    full_name: client.name || '',
    phone: client.phone || '',
    company: client.company || '',
    private_notes: client.privateNotes || '',
  });
  const [saveState, setSaveState] = React.useState({ saving: false, message: '', error: '' });
  const sectionTitle = { fontFamily: '"Barlow Condensed", sans-serif', fontSize: '24px', fontWeight: '800', color: '#1B2A4A', margin: '0 0 14px 0' };
  const field = { fontFamily: 'Inter, sans-serif', fontSize: '14px', fontWeight: '600', color: '#1B2A4A', border: '1.5px solid #E2E8F0', borderRadius: '8px', padding: '10px 14px', width: '100%', boxSizing: 'border-box', outline: 'none' };
  const set = (key, value) => setForm((state) => ({ ...state, [key]: value }));
  const activeRentals = client.rentals.filter((rental) => rental.status === 'active');
  const closedRentals = client.rentals.filter((rental) => rental.status !== 'active');
  const allQuotes = [...client.quotes].sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
  const currentSales = [...client.currentSales].sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
  const pastSales = [...client.pastSales].sort((a, b) => new Date(b.created_at) - new Date(a.created_at));

  const save = async () => {
    setSaveState({ saving: true, message: '', error: '' });
    try {
      await onSave({
        full_name: form.full_name.trim(),
        phone: form.phone.trim(),
        company: form.company.trim(),
        private_notes: form.private_notes.trim(),
      });
      setSaveState({ saving: false, message: 'CRM details saved.', error: '' });
    } catch (error) {
      setSaveState({ saving: false, message: '', error: error.message || 'Unable to save CRM details.' });
    }
  };

  const renderQuoteList = (items, emptyText) => (
    items.length === 0 ? (
      <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#9AAAB8' }}>{emptyText}</div>
    ) : (
      <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
        {items.map((quote) => (
          <button key={quote.id} type="button" onClick={() => onEditQuote(quote)} style={{ textAlign: 'left', background: '#F8FBFD', border: '1px solid #E4EEF5', borderRadius: '10px', padding: '12px 14px', cursor: 'pointer' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', gap: '12px', marginBottom: '4px' }}>
              <span style={{ fontFamily: 'Inter, sans-serif', fontSize: '14px', fontWeight: '700', color: '#1B2A4A' }}>{quote.interest === 'rental' ? 'Rental Quote' : 'Sale Quote'} · {formatQuoteSizeLabel(quote.size) || 'Size TBD'}</span>
              <span style={{ fontFamily: 'Inter, sans-serif', fontSize: '11px', fontWeight: '700', color: '#6B7E96', textTransform: 'uppercase' }}>{quote.status || 'pending'}</span>
            </div>
            <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '12px', color: '#6B7E96' }}>{quote.condition || 'Condition TBD'} · {quote.zip ? `ZIP ${quote.zip}` : 'ZIP TBD'} · {quote.created_at ? new Date(quote.created_at).toLocaleDateString() : 'No date'}</div>
            {quote.quoted_price ? <div style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '22px', fontWeight: '800', color: '#4A9FD4', marginTop: '6px' }}>{formatMoney(quote.quoted_price)}</div> : null}
          </button>
        ))}
      </div>
    )
  );

  const renderRentalList = (items, emptyText) => (
    items.length === 0 ? (
      <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#9AAAB8' }}>{emptyText}</div>
    ) : (
      <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
        {items.map((rental) => (
          <button key={rental.id} type="button" onClick={() => onEditRental(rental)} style={{ textAlign: 'left', background: '#F8FBFD', border: '1px solid #E4EEF5', borderRadius: '10px', padding: '12px 14px', cursor: 'pointer' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', gap: '12px', marginBottom: '4px' }}>
              <span style={{ fontFamily: 'Inter, sans-serif', fontSize: '14px', fontWeight: '700', color: '#1B2A4A' }}>{rental.container_type}</span>
              <span style={{ fontFamily: 'Inter, sans-serif', fontSize: '11px', fontWeight: '700', color: '#6B7E96', textTransform: 'uppercase' }}>{rental.status || 'active'}</span>
            </div>
            <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '12px', color: '#6B7E96' }}>Started {rental.start_date ? new Date(rental.start_date).toLocaleDateString() : 'Unknown'} · {formatMoney(rental.monthly_rate)}/mo</div>
            {rental.notes ? <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '12px', color: '#4A5568', marginTop: '6px' }}>{rental.notes}</div> : null}
          </button>
        ))}
      </div>
    )
  );

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '0.9fr 1.1fr', gap: '22px' }} className="crm-grid">
      <div style={{ display: 'flex', flexDirection: 'column', gap: '18px' }}>
        <div style={{ background: 'linear-gradient(135deg, #10233B 0%, #1B2A4A 100%)', borderRadius: '14px', padding: '20px 22px', color: '#fff' }}>
          <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '11px', fontWeight: '700', letterSpacing: '0.08em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.55)', marginBottom: '8px' }}>Client Contact Card</div>
          <div style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '34px', fontWeight: '800', lineHeight: 1 }}>{form.full_name || client.name || 'Unknown Client'}</div>
          <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '14px', color: 'rgba(255,255,255,0.72)', marginTop: '6px' }}>{client.email}</div>
          {form.company && <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '13px', color: 'rgba(255,255,255,0.62)', marginTop: '6px' }}>{form.company}</div>}
        </div>

        <div style={{ background: '#fff', border: '1px solid #E8EDF2', borderRadius: '12px', padding: '20px' }}>
          <div style={sectionTitle}>Contact Info</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
            <div>
              <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Full Name</label>
              <input value={form.full_name} onChange={(e) => set('full_name', e.target.value)} style={field} />
            </div>
            <div>
              <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Email</label>
              <input value={client.email} disabled style={{ ...field, background: '#F9FAFB', color: '#9AAAB8' }} />
            </div>
            <div>
              <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Phone</label>
              <input value={form.phone} onChange={(e) => set('phone', e.target.value)} style={field} />
            </div>
            <div>
              <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Company</label>
              <input value={form.company} onChange={(e) => set('company', e.target.value)} style={field} placeholder="Optional company or account name" />
            </div>
          </div>
        </div>

        <div style={{ background: '#fff', border: '1px solid #E8EDF2', borderRadius: '12px', padding: '20px' }}>
          <div style={sectionTitle}>Private Notes</div>
          <textarea value={form.private_notes} onChange={(e) => set('private_notes', e.target.value)} rows={8} style={{ ...field, resize: 'vertical' }} placeholder="Internal notes, follow-ups, buying preferences, payment details, delivery quirks..." />
          <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginTop: '14px' }}>
            <button type="button" onClick={save} disabled={saveState.saving} style={{ background: saveState.saving ? '#9AAAB8' : '#1B2A4A', color: '#fff', border: 'none', borderRadius: '8px', padding: '12px 20px', cursor: saveState.saving ? 'not-allowed' : 'pointer', fontFamily: 'Inter, sans-serif', fontSize: '14px', fontWeight: '700' }}>
              {saveState.saving ? 'Saving…' : 'Save CRM Notes'}
            </button>
            {saveState.message && <span style={{ fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#38A169', fontWeight: '600' }}>{saveState.message}</span>}
            {saveState.error && <span style={{ fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#C53030', fontWeight: '600' }}>{saveState.error}</span>}
          </div>
        </div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: '18px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px' }}>
          {[
            { label: 'Quotes', value: client.quotes.length, color: '#4A9FD4' },
            { label: 'Active Rentals', value: activeRentals.length, color: '#38A169' },
            { label: 'Open Sales', value: currentSales.length, color: '#D69E2E' },
            { label: 'Closed Sales', value: pastSales.length, color: '#1B2A4A' },
          ].map((item) => (
            <div key={item.label} style={{ background: '#fff', border: '1px solid #E8EDF2', borderRadius: '12px', padding: '16px' }}>
              <div style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '32px', fontWeight: '800', color: item.color, lineHeight: 1 }}>{item.value}</div>
              <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '12px', fontWeight: '700', color: '#6B7E96', marginTop: '4px' }}>{item.label}</div>
            </div>
          ))}
        </div>

        <div style={{ background: '#fff', border: '1px solid #E8EDF2', borderRadius: '12px', padding: '20px' }}>
          <div style={sectionTitle}>Quotes</div>
          {renderQuoteList(allQuotes, 'No quotes for this client yet.')}
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '18px' }}>
          <div style={{ background: '#fff', border: '1px solid #E8EDF2', borderRadius: '12px', padding: '20px' }}>
            <div style={sectionTitle}>Current Sales</div>
            {renderQuoteList(currentSales, 'No open sale quotes.')}
          </div>
          <div style={{ background: '#fff', border: '1px solid #E8EDF2', borderRadius: '12px', padding: '20px' }}>
            <div style={sectionTitle}>Past Sales</div>
            {renderQuoteList(pastSales, 'No completed sale history yet.')}
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '18px' }}>
          <div style={{ background: '#fff', border: '1px solid #E8EDF2', borderRadius: '12px', padding: '20px' }}>
            <div style={sectionTitle}>Active Rentals</div>
            {renderRentalList(activeRentals, 'No active rentals.')}
          </div>
          <div style={{ background: '#fff', border: '1px solid #E8EDF2', borderRadius: '12px', padding: '20px' }}>
            <div style={sectionTitle}>Past Rentals</div>
            {renderRentalList(closedRentals, 'No past rental history yet.')}
          </div>
        </div>
      </div>

      <style>{`@media (max-width: 980px) { .crm-grid { grid-template-columns: 1fr !important; } }`}</style>
    </div>
  );
};

// ── Quote Edit Form ───────────────────────────────────────────────────────────
const QuoteEditForm = ({ quote, pricing, onSave, onDraftSave, onSent }) => {
  const [status, setStatus] = React.useState(quote.status || 'pending');
  const [notes, setNotes] = React.useState(quote.admin_notes || '');
  const [price, setPrice] = React.useState(quote.quoted_price || '');
  const [sendState, setSendState] = React.useState({ sending: false, message: '', error: '' });
  const [draftSaveState, setDraftSaveState] = React.useState({ saving: false, savedAt: '', error: '' });
  const [deliveryEstimateState, setDeliveryEstimateState] = React.useState({ loading: false, miles: null, fee: null, outOfRange: false, warning: '' });
  const [builderDraft, setBuilderDraft] = React.useState(() => {
    try {
      if (quote.quote_builder && typeof quote.quote_builder === 'object') {
        return { ...buildDefaultQuoteDraft(quote, pricing), ...quote.quote_builder };
      }
      const saved = localStorage.getItem(getQuoteDraftStorageKey(quote.id));
      return saved ? JSON.parse(saved) : buildDefaultQuoteDraft(quote, pricing);
    } catch {
      return buildDefaultQuoteDraft(quote, pricing);
    }
  });

  React.useEffect(() => {
    try {
      localStorage.setItem(getQuoteDraftStorageKey(quote.id), JSON.stringify(builderDraft));
    } catch {}
  }, [quote.id, builderDraft]);

  React.useEffect(() => {
    if (!SUPABASE_CONFIGURED || !onDraftSave) return undefined;

    const timeoutId = window.setTimeout(async () => {
      try {
        setDraftSaveState((state) => ({ ...state, saving: true, error: '' }));
        await onDraftSave({ quote_builder: builderDraft });
        setDraftSaveState({ saving: false, savedAt: new Date().toLocaleTimeString(), error: '' });
      } catch (error) {
        setDraftSaveState({ saving: false, savedAt: '', error: error.message || 'Unable to save quote draft.' });
      }
    }, 900);

    return () => window.clearTimeout(timeoutId);
  }, [builderDraft, onDraftSave]);

  React.useEffect(() => {
    const zip = String(quote.zip || '').replace(/\D/g, '').slice(0, 5);
    if (zip.length !== 5 || !pricing) {
      setDeliveryEstimateState({ loading: false, miles: null, fee: null, outOfRange: false, warning: '' });
      return undefined;
    }

    const controller = new AbortController();
    setDeliveryEstimateState((state) => ({ ...state, loading: true, warning: '' }));

    (async () => {
      try {
        const response = await fetch(`/api/delivery-distance?zip=${encodeURIComponent(zip)}`, {
          signal: controller.signal,
        });
        if (!response.ok) throw new Error('Unable to calculate delivery distance.');
        const payload = await response.json();
        const miles = typeof payload.miles === 'number' ? payload.miles : null;
        const fee = computeDeliveryEstimateFromMiles(miles, pricing, builderDraft.quoteKind);
        const outOfRange = payload.outOfRange || fee === 'out-of-range';
        setDeliveryEstimateState({
          loading: false,
          miles,
          fee: typeof fee === 'number' ? fee : null,
          outOfRange,
          warning: payload.warning || '',
        });
      } catch (error) {
        if (controller.signal.aborted) return;
        setDeliveryEstimateState({
          loading: false,
          miles: null,
          fee: null,
          outOfRange: false,
          warning: error?.message || 'Unable to calculate delivery distance.',
        });
      }
    })();

    return () => controller.abort();
  }, [quote.zip, pricing, builderDraft.quoteKind]);

  React.useEffect(() => {
    const normalizedTaxRate = String(normalizeTaxRateDecimal(pricing?.tax_rate || 0));
    setBuilderDraft((draft) => {
      const nextDraft = { ...draft };
      let changed = false;

      if (normalizeTaxRateDecimal(nextDraft.taxRate) === 0 && normalizeTaxRateDecimal(normalizedTaxRate) > 0) {
        nextDraft.taxRate = normalizedTaxRate;
        changed = true;
      }

      if (String(nextDraft.deliveryFee || '').trim() === '' && typeof deliveryEstimateState.fee === 'number' && !deliveryEstimateState.outOfRange) {
        nextDraft.deliveryFee = deliveryEstimateState.fee.toFixed(2);
        changed = true;
      }

      return changed ? nextDraft : draft;
    });
  }, [pricing, deliveryEstimateState.fee, deliveryEstimateState.outOfRange]);

  const fld = { fontFamily: 'Inter, sans-serif', fontSize: '14px', fontWeight: '600', color: '#1B2A4A', border: '1.5px solid #E2E8F0', borderRadius: '8px', padding: '10px 14px', width: '100%', boxSizing: 'border-box', outline: 'none' };
  const totals = computeQuoteBuilderTotals(builderDraft);
  const effectivePrice = price === '' ? totals.total : toMoneyNumber(price);
  const validUntil = new Date(Date.now() + (Math.max(1, Number(builderDraft.validDays) || 7) * 24 * 60 * 60 * 1000)).toLocaleDateString();
  const isRentalQuote = builderDraft.quoteKind === 'rental';

  const setDraft = (key, value) => setBuilderDraft((draft) => ({ ...draft, [key]: value }));
  const updateItem = (itemId, patch) => {
    setBuilderDraft((draft) => ({
      ...draft,
      lineItems: draft.lineItems.map((item) => (item.id === itemId ? { ...item, ...patch } : item)),
    }));
  };
  const addItem = () => setBuilderDraft((draft) => ({ ...draft, lineItems: [...draft.lineItems, createQuoteBuilderItem()] }));
  const removeItem = (itemId) => setBuilderDraft((draft) => ({
    ...draft,
    lineItems: draft.lineItems.length > 1 ? draft.lineItems.filter((item) => item.id !== itemId) : draft.lineItems,
  }));
  const setQuoteKind = (value) => {
    const nextKind = value === 'rental' ? 'rental' : 'sale';
    setBuilderDraft((draft) => ({
      ...draft,
      quoteKind: nextKind,
      quoteTitle: draft.quoteTitle === 'Container Quote' || draft.quoteTitle === 'Rental Quote'
        ? (nextKind === 'rental' ? 'Rental Quote' : 'Container Quote')
        : draft.quoteTitle,
    }));
  };

  const saveOnly = () => onSave({ status, interest: builderDraft.quoteKind, admin_notes: notes, quoted_price: effectivePrice, quote_builder: builderDraft });

  const sendQuote = async () => {
    setSendState({ sending: true, message: '', error: '' });
    try {
      const token = (typeof localStorage !== 'undefined' && localStorage.getItem('sss_token')) || supa._token || '';
      const response = await fetch('/api/admin/send-quote', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          ...(token ? { Authorization: `Bearer ${token}` } : {}),
        },
        body: JSON.stringify({
          quoteId: quote.id,
          status: 'quoted',
          clientNote: notes,
          quotedPrice: effectivePrice,
          builder: {
            ...builderDraft,
            lineItems: totals.lineItems,
            totalOverride: effectivePrice,
          },
        }),
      });
      const payload = await response.json().catch(() => ({}));
      if (!response.ok || !payload.ok) {
        throw new Error(payload.message || 'Unable to send quote right now.');
      }

      try {
        localStorage.removeItem(getQuoteDraftStorageKey(quote.id));
      } catch {}

      setSendState({ sending: false, message: 'Quote email and PDF sent.', error: '' });
      onSent(payload.quote || { ...quote, status: 'quoted', interest: builderDraft.quoteKind, quoted_price: effectivePrice, admin_notes: notes, quote_builder: builderDraft });
    } catch (error) {
      setSendState({ sending: false, message: '', error: error.message || 'Unable to send quote right now.' });
    }
  };

  return (
    <div>
      <div style={{ background: 'linear-gradient(135deg, #10233B 0%, #1B2A4A 100%)', borderRadius: '12px', padding: '20px 22px', marginBottom: '22px', color: '#fff' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', gap: '16px', alignItems: 'flex-start', flexWrap: 'wrap' }}>
          <div>
            <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '11px', fontWeight: '700', letterSpacing: '0.08em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.55)', marginBottom: '6px' }}>Quote Record</div>
            <div style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '30px', fontWeight: '800', lineHeight: 1.05 }}>{quote.name}</div>
            <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '14px', color: 'rgba(255,255,255,0.72)', marginTop: '6px' }}>{quote.email}{quote.phone ? ` · ${quote.phone}` : ''}</div>
          </div>
          <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
            {[quote.interest || 'quote', quote.size || 'size TBD', quote.condition || 'condition TBD', `ZIP ${quote.zip}`].map((tag) => (
              <span key={tag} style={{ background: 'rgba(255,255,255,0.1)', border: '1px solid rgba(255,255,255,0.14)', borderRadius: '999px', padding: '6px 12px', fontFamily: 'Inter, sans-serif', fontSize: '12px', color: '#D7E7F4', fontWeight: '600' }}>
                {tag}
              </span>
            ))}
          </div>
        </div>
        {quote.message && (
          <p style={{ margin: '16px 0 0 0', fontFamily: 'Inter, sans-serif', fontSize: '14px', lineHeight: '1.65', color: 'rgba(255,255,255,0.78)' }}>
            “{quote.message}”
          </p>
        )}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 0.9fr', gap: '22px' }} className="quote-builder-grid">
        <div style={{ display: 'flex', flexDirection: 'column', gap: '18px' }}>
          <div style={{ background: '#F8FBFD', border: '1px solid #E4EEF5', borderRadius: '12px', padding: '20px' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px', gap: '10px', flexWrap: 'wrap' }}>
              <div>
                <div style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '26px', fontWeight: '800', color: '#1B2A4A' }}>Quote Builder</div>
                <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#6B7E96' }}>Build the pricing structure and the branded quote message.</div>
              </div>
              <button type="button" onClick={addItem} style={{ background: '#1B2A4A', color: '#fff', border: 'none', borderRadius: '8px', padding: '10px 16px', cursor: 'pointer', fontFamily: 'Inter, sans-serif', fontSize: '13px', fontWeight: '700' }}>
                + Add Line Item
              </button>
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: '0.85fr 1fr 1fr', gap: '14px', marginBottom: '16px' }}>
              <div>
                <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Quote Type</label>
                <select value={builderDraft.quoteKind || 'sale'} onChange={e => setQuoteKind(e.target.value)} style={{ ...fld, cursor: 'pointer' }}>
                  <option value="sale">Sale</option>
                  <option value="rental">Rental</option>
                </select>
              </div>
              <div>
                <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Email Subject</label>
                <input value={builderDraft.subject} onChange={e => setDraft('subject', e.target.value)} style={fld} placeholder="Your Sea Steel Storage Quote" />
              </div>
              <div>
                <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Quote Title</label>
                <input value={builderDraft.quoteTitle} onChange={e => setDraft('quoteTitle', e.target.value)} style={fld} placeholder="Container Quote" />
              </div>
            </div>

            <div style={{ marginBottom: '16px' }}>
              <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Intro Message</label>
              <textarea value={builderDraft.intro} onChange={e => setDraft('intro', e.target.value)} rows={3} style={{ ...fld, resize: 'vertical' }} placeholder="Thanks for reaching out..." />
            </div>

            {isRentalQuote && (
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '12px', marginBottom: '16px' }}>
                <div>
                  <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Term Length (months)</label>
                  <input type="number" min="1" step="1" value={builderDraft.rentalTermMonths} onChange={e => setDraft('rentalTermMonths', e.target.value)} style={fld} placeholder="6" />
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Monthly Rate Override</label>
                  <input type="number" min="0" step="0.01" value={builderDraft.rentalMonthlyRate} onChange={e => setDraft('rentalMonthlyRate', e.target.value)} style={fld} placeholder={`Auto: ${formatMoney(totals.itemsSubtotal)}`} />
                </div>
                <div>
                  <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Deposit</label>
                  <input type="number" min="0" step="0.01" value={builderDraft.rentalDeposit} onChange={e => setDraft('rentalDeposit', e.target.value)} style={fld} placeholder="0.00" />
                </div>
              </div>
            )}

            <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
              {builderDraft.lineItems.map((item, index) => (
                <div key={item.id} style={{ background: '#fff', border: '1px solid #E2E8F0', borderRadius: '12px', padding: '14px' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '10px' }}>
                    <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '12px', fontWeight: '700', color: '#6B7E96', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Line Item {index + 1}</div>
                    {builderDraft.lineItems.length > 1 && (
                      <button type="button" onClick={() => removeItem(item.id)} style={{ background: 'none', border: 'none', color: '#E53E3E', cursor: 'pointer', fontFamily: 'Inter, sans-serif', fontSize: '12px', fontWeight: '700' }}>
                        Remove
                      </button>
                    )}
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 0.45fr 0.7fr', gap: '10px', marginBottom: '10px' }}>
                    <input value={item.label} onChange={e => updateItem(item.id, { label: e.target.value })} style={fld} placeholder="Container or service" />
                    <input type="number" min="1" value={item.quantity} onChange={e => updateItem(item.id, { quantity: e.target.value })} style={fld} placeholder="Qty" />
                    <input type="number" min="0" step="0.01" value={item.unitPrice} onChange={e => updateItem(item.id, { unitPrice: e.target.value })} style={fld} placeholder="Unit price" />
                  </div>
                  <textarea value={item.description} onChange={e => updateItem(item.id, { description: e.target.value })} rows={2} style={{ ...fld, resize: 'vertical' }} placeholder="Optional description or scope notes" />
                </div>
              ))}
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginTop: '16px' }}>
              <div>
                <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Delivery Fee</label>
                <input type="number" min="0" step="0.01" value={builderDraft.deliveryFee} onChange={e => setDraft('deliveryFee', e.target.value)} style={fld} placeholder="0.00" />
                {quote.zip ? (
                  <div style={{ marginTop: '6px', fontFamily: 'Inter, sans-serif', fontSize: '11px', color: deliveryEstimateState.outOfRange ? '#E53E3E' : '#9AAAB8', lineHeight: '1.5' }}>
                    {deliveryEstimateState.loading
                      ? 'Calculating delivery estimate from quote ZIP...'
                      : deliveryEstimateState.outOfRange
                        ? `ZIP ${quote.zip} is outside the configured service radius.`
                        : typeof deliveryEstimateState.fee === 'number' && typeof deliveryEstimateState.miles === 'number'
                          ? `Suggested delivery: ${formatMoney(deliveryEstimateState.fee)} for ~${deliveryEstimateState.miles} miles`
                          : deliveryEstimateState.warning || `Using ZIP ${quote.zip} for delivery pricing when available.`}
                  </div>
                ) : null}
              </div>
              <div>
                <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Discount</label>
                <input type="number" min="0" step="0.01" value={builderDraft.discount} onChange={e => setDraft('discount', e.target.value)} style={fld} placeholder="0.00" />
              </div>
              <div>
                <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Tax Rate (decimal)</label>
                <input type="number" min="0" step="0.01" value={builderDraft.taxRate} onChange={e => setDraft('taxRate', e.target.value)} style={fld} placeholder="0.10" />
              </div>
              <div>
                <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Valid For (days)</label>
                <input type="number" min="1" step="1" value={builderDraft.validDays} onChange={e => setDraft('validDays', e.target.value)} style={fld} placeholder="7" />
              </div>
            </div>

            <div style={{ marginTop: '16px' }}>
              <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Terms / Fine Print</label>
              <textarea value={builderDraft.terms} onChange={e => setDraft('terms', e.target.value)} rows={3} style={{ ...fld, resize: 'vertical' }} placeholder="Quote subject to inventory availability..." />
            </div>

            <div style={{ marginTop: '16px' }}>
              <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Closing Message</label>
              <textarea value={builderDraft.footer} onChange={e => setDraft('footer', e.target.value)} rows={3} style={{ ...fld, resize: 'vertical' }} placeholder="Reply or call us to revise the quote..." />
            </div>
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: '18px' }}>
          <div style={{ background: '#fff', border: '1px solid #E2E8F0', borderRadius: '12px', padding: '20px' }}>
            <div style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '24px', fontWeight: '800', color: '#1B2A4A', marginBottom: '14px' }}>Quote Controls</div>
            <div style={{ marginBottom: '14px' }}>
              <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Status</label>
              <select value={status} onChange={e => setStatus(e.target.value)} style={{ ...fld, cursor: 'pointer' }}>
                {['pending', 'quoted', 'active', 'completed', 'cancelled'].map(s => <option key={s} value={s}>{s}</option>)}
              </select>
            </div>
            <div style={{ marginBottom: '14px' }}>
              <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Quoted Price Override ($)</label>
              <input type="number" min="0" step="0.01" value={price} onChange={e => setPrice(e.target.value)} style={fld} placeholder={`Auto: ${formatMoney(totals.total)}`} />
            </div>
            <div style={{ marginBottom: '14px' }}>
              <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Client-Facing Note</label>
              <textarea value={notes} onChange={e => setNotes(e.target.value)} rows={4} style={{ ...fld, resize: 'vertical' }} placeholder="Short note that will also appear on the client portal." />
            </div>
            <div style={{ background: 'linear-gradient(135deg, #1B2A4A, #243a5e)', borderRadius: '12px', padding: '18px', color: '#fff', marginBottom: '14px' }}>
              <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '11px', letterSpacing: '0.08em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.55)', marginBottom: '6px' }}>{totals.totalLabel}</div>
              <div style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '42px', fontWeight: '800', lineHeight: 1 }}>{formatMoney(effectivePrice)}</div>
              {isRentalQuote && (
                <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '12px', color: 'rgba(255,255,255,0.76)', marginTop: '6px' }}>
                  {formatMoney(totals.monthlyRate)}/mo for {totals.rentalTermMonths} months · Due at signing {formatMoney(totals.dueAtSigningTotal)}
                </div>
              )}
              <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '12px', color: 'rgba(255,255,255,0.6)', marginTop: '6px' }}>Valid until {validUntil}</div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
              <button type="button" onClick={sendQuote} disabled={sendState.sending || totals.lineItems.length === 0} style={{ width: '100%', background: sendState.sending ? '#9AAAB8' : '#4A9FD4', color: '#fff', border: 'none', borderRadius: '10px', padding: '14px', cursor: sendState.sending ? 'not-allowed' : 'pointer', fontFamily: 'Inter, sans-serif', fontSize: '15px', fontWeight: '700' }}>
                {sendState.sending ? 'Sending Quote…' : 'Send Quote Email + PDF'}
              </button>
              <button type="button" onClick={saveOnly} style={{ width: '100%', background: '#1B2A4A', color: '#fff', border: 'none', borderRadius: '10px', padding: '13px', cursor: 'pointer', fontFamily: 'Inter, sans-serif', fontSize: '14px', fontWeight: '700' }}>
                Save Quote Draft
              </button>
              <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '12px', color: '#9AAAB8', lineHeight: '1.5' }}>
                Builder draft autosaves in this browser while you work.
              </div>
              {draftSaveState.saving && <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '12px', color: '#9AAAB8' }}>Saving draft…</div>}
              {!draftSaveState.saving && draftSaveState.savedAt && <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '12px', color: '#38A169' }}>Draft saved at {draftSaveState.savedAt}</div>}
              {draftSaveState.error && <div style={{ background: '#FFF5F5', border: '1px solid #FEB2B2', borderRadius: '8px', padding: '10px 12px', fontFamily: 'Inter, sans-serif', fontSize: '12px', color: '#C53030' }}>{draftSaveState.error}</div>}
              {sendState.message && <div style={{ background: '#F0FFF4', border: '1px solid #9AE6B4', borderRadius: '8px', padding: '10px 12px', fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#276749' }}>{sendState.message}</div>}
              {sendState.error && <div style={{ background: '#FFF5F5', border: '1px solid #FEB2B2', borderRadius: '8px', padding: '10px 12px', fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#C53030' }}>{sendState.error}</div>}
            </div>
          </div>

          <div style={{ background: '#fff', border: '1px solid #E2E8F0', borderRadius: '12px', overflow: 'hidden' }}>
            <div style={{ background: 'linear-gradient(135deg, #10233B 0%, #1B2A4A 100%)', padding: '18px 20px', color: '#fff' }}>
              <div style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '24px', fontWeight: '800' }}>{builderDraft.quoteTitle || 'Container Quote'}</div>
              <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '13px', color: 'rgba(255,255,255,0.68)' }}>Preview of the email and PDF content</div>
            </div>
            <div style={{ padding: '20px' }}>
              <p style={{ fontFamily: 'Inter, sans-serif', fontSize: '14px', color: '#4A5568', lineHeight: '1.7', margin: '0 0 14px 0' }}>{builderDraft.intro}</p>
              {isRentalQuote && (
                <div style={{ background: '#F8FBFD', border: '1px solid #E4EEF5', borderRadius: '10px', padding: '14px 16px', marginBottom: '16px' }}>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: '10px', fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#4A5568' }}>
                    <span>Term Length</span><strong style={{ color: '#1B2A4A' }}>{totals.rentalTermMonths} months</strong>
                    <span>Monthly Rate</span><strong style={{ color: '#1B2A4A' }}>{formatMoney(totals.monthlyRate)}/mo</strong>
                    <span>Deposit</span><strong style={{ color: '#1B2A4A' }}>{formatMoney(totals.rentalDeposit)}</strong>
                    <span>Due at Signing</span><strong style={{ color: '#1B2A4A' }}>{formatMoney(totals.dueAtSigningTotal)}</strong>
                  </div>
                </div>
              )}
              <div style={{ display: 'flex', flexDirection: 'column', gap: '10px', marginBottom: '16px' }}>
                {totals.lineItems.map((item) => (
                  <div key={item.id} style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: '12px', paddingBottom: '10px', borderBottom: '1px solid #EEF2F7' }}>
                    <div>
                      <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '14px', fontWeight: '700', color: '#1B2A4A' }}>{item.label}</div>
                      {item.description && <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '12px', color: '#6B7E96', marginTop: '4px', lineHeight: '1.5' }}>{item.description}</div>}
                      <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '11px', color: '#9AAAB8', marginTop: '4px' }}>Qty {item.quantity} × {formatMoney(item.unitPrice)}</div>
                    </div>
                    <div style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '24px', fontWeight: '800', color: '#1B2A4A' }}>{formatMoney(item.quantity * item.unitPrice)}</div>
                  </div>
                ))}
              </div>
              <div style={{ background: '#F8FBFD', border: '1px solid #E4EEF5', borderRadius: '10px', padding: '16px', marginBottom: '16px' }}>
                {isRentalQuote ? (
                  <>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#6B7E96', marginBottom: '6px' }}><span>Monthly Items</span><span>{formatMoney(totals.itemsSubtotal)}</span></div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#6B7E96', marginBottom: '6px' }}><span>Monthly Rate</span><span>{formatMoney(totals.monthlyRate)}/mo</span></div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#6B7E96', marginBottom: '6px' }}><span>Deposit</span><span>{formatMoney(totals.rentalDeposit)}</span></div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#6B7E96', marginBottom: '6px' }}><span>Delivery</span><span>{formatMoney(totals.deliveryFee)}</span></div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#6B7E96', marginBottom: '6px' }}><span>Discount</span><span>-{formatMoney(totals.discount)}</span></div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#6B7E96', marginBottom: '6px' }}><span>Due at Signing</span><span>{formatMoney(totals.dueAtSigningTotal)}</span></div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#6B7E96', marginBottom: '10px' }}><span>Estimated Tax ({formatTaxRatePercent(totals.taxRate)})</span><span>{formatMoney(totals.taxAmount)}</span></div>
                  </>
                ) : (
                  <>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#6B7E96', marginBottom: '6px' }}><span>Items</span><span>{formatMoney(totals.itemsSubtotal)}</span></div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#6B7E96', marginBottom: '6px' }}><span>Delivery</span><span>{formatMoney(totals.deliveryFee)}</span></div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#6B7E96', marginBottom: '6px' }}><span>Discount</span><span>-{formatMoney(totals.discount)}</span></div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#6B7E96', marginBottom: '10px' }}><span>Tax ({formatTaxRatePercent(totals.taxRate)})</span><span>{formatMoney(totals.taxAmount)}</span></div>
                  </>
                )}
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}><span style={{ fontFamily: 'Inter, sans-serif', fontSize: '12px', fontWeight: '700', letterSpacing: '0.08em', color: '#6B7E96', textTransform: 'uppercase' }}>{totals.totalLabel}</span><span style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '34px', fontWeight: '800', color: '#1B2A4A' }}>{formatMoney(effectivePrice)}</span></div>
              </div>
              {notes && <p style={{ fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#2B6CB0', background: '#EBF8FF', borderLeft: '3px solid #4A9FD4', padding: '10px 12px', margin: '0 0 14px 0' }}>{notes}</p>}
              <p style={{ fontFamily: 'Inter, sans-serif', fontSize: '12px', color: '#6B7E96', lineHeight: '1.6', margin: '0 0 12px 0' }}>{builderDraft.terms}</p>
              <p style={{ fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#4A5568', lineHeight: '1.6', margin: 0 }}>{builderDraft.footer}</p>
            </div>
          </div>
        </div>
      </div>

      <style>{`@media (max-width: 900px) { .quote-builder-grid { grid-template-columns: 1fr !important; } }`}</style>
    </div>
  );
};

// ── Rental Edit Form ──────────────────────────────────────────────────────────
const RentalEditForm = ({ rental, profiles, onSave }) => {
  const clientProfiles = profiles.filter((profile) => !profile.is_admin && profile.email);
  const [error, setError] = React.useState('');
  const [form, setForm] = React.useState({
    customer_name: rental?.customer_name || '',
    customer_email: rental?.customer_email || '',
    user_id: rental?.user_id || '',
    container_type: rental?.container_type || "20' New",
    monthly_rate: rental?.monthly_rate || 120,
    start_date: rental?.start_date || new Date().toISOString().split('T')[0],
    status: rental?.status || 'active',
    delivery_cost: rental?.delivery_cost || '',
    container_sale_price: rental?.container_sale_price || '',
    residual_value: rental?.residual_value || '',
    notes: rental?.notes || '',
  });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const applyClient = (profileId) => {
    const profile = clientProfiles.find((item) => item.id === profileId);
    if (!profile) return;
    setForm((state) => ({
      ...state,
      user_id: profile.id,
      customer_name: profile.full_name || state.customer_name,
      customer_email: profile.email || state.customer_email,
    }));
  };
  const save = () => {
    if (!form.customer_name.trim()) {
      setError('Customer name is required.');
      return;
    }
    if (!normalizeClientEmail(form.customer_email) || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(normalizeClientEmail(form.customer_email))) {
      setError('A valid customer email is required so the rental can link to the client portal.');
      return;
    }
    setError('');
    const matchedProfile = findClientProfileByEmail(profiles, form.customer_email);
    onSave({
      ...form,
      customer_name: form.customer_name.trim(),
      customer_email: normalizeClientEmail(form.customer_email),
      user_id: matchedProfile?.id || form.user_id || null,
      delivery_cost: form.delivery_cost === '' ? '' : Number(form.delivery_cost),
      container_sale_price: form.container_sale_price === '' ? '' : Number(form.container_sale_price),
      residual_value: form.residual_value === '' ? '' : Number(form.residual_value),
      notes: form.notes.trim(),
    });
  };
  const fld = { fontFamily: 'Inter, sans-serif', fontSize: '14px', fontWeight: '600', color: '#1B2A4A', border: '1.5px solid #E2E8F0', borderRadius: '8px', padding: '10px 14px', width: '100%', boxSizing: 'border-box', outline: 'none' };
  const Label = ({ children }) => <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>{children}</label>;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '14px' }}>
      <div>
        <Label>Existing Client</Label>
        <select value="" onChange={e => applyClient(e.target.value)} style={{ ...fld, cursor: 'pointer' }}>
          <option value="">Select existing client or enter manually</option>
          {clientProfiles.map((profile) => <option key={profile.id} value={profile.id}>{profile.full_name || profile.email} · {profile.email}</option>)}
        </select>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
        <div>
          <Label>Customer Name</Label>
          <input value={form.customer_name} onChange={e => set('customer_name', e.target.value)} style={fld} placeholder="Jane Smith" onFocus={e => e.target.style.borderColor='#4A9FD4'} onBlur={e => e.target.style.borderColor='#E2E8F0'} />
        </div>
        <div>
          <Label>Customer Email</Label>
          <input type="email" value={form.customer_email} onChange={e => set('customer_email', e.target.value)} style={fld} placeholder="jane@example.com" onFocus={e => e.target.style.borderColor='#4A9FD4'} onBlur={e => e.target.style.borderColor='#E2E8F0'} />
        </div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
        <div>
          <Label>Container Type</Label>
          <select value={form.container_type} onChange={e => set('container_type', e.target.value)} style={{ ...fld, cursor: 'pointer' }}>
            {["20' New", "20' Used", "40' New HC", "40' Used"].map(t => <option key={t}>{t}</option>)}
          </select>
        </div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
        <div>
          <Label>Monthly Rate ($)</Label>
          <input type="number" value={form.monthly_rate} onChange={e => set('monthly_rate', Number(e.target.value))} style={fld} onFocus={e => e.target.style.borderColor='#4A9FD4'} onBlur={e => e.target.style.borderColor='#E2E8F0'} />
        </div>
        <div>
          <Label>Start Date</Label>
          <input type="date" value={form.start_date} onChange={e => set('start_date', e.target.value)} style={fld} onFocus={e => e.target.style.borderColor='#4A9FD4'} onBlur={e => e.target.style.borderColor='#E2E8F0'} />
        </div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '12px' }}>
        <div>
          <Label>Delivery Cost ($)</Label>
          <input type="number" value={form.delivery_cost} onChange={e => set('delivery_cost', e.target.value)} style={fld} onFocus={e => e.target.style.borderColor='#4A9FD4'} onBlur={e => e.target.style.borderColor='#E2E8F0'} />
        </div>
        <div>
          <Label>Sale Price ($)</Label>
          <input type="number" value={form.container_sale_price} onChange={e => set('container_sale_price', e.target.value)} style={fld} onFocus={e => e.target.style.borderColor='#4A9FD4'} onBlur={e => e.target.style.borderColor='#E2E8F0'} />
        </div>
        <div>
          <Label>Residual Value ($)</Label>
          <input type="number" value={form.residual_value} onChange={e => set('residual_value', e.target.value)} style={fld} onFocus={e => e.target.style.borderColor='#4A9FD4'} onBlur={e => e.target.style.borderColor='#E2E8F0'} />
        </div>
      </div>
      <div>
        <Label>Status</Label>
        <select value={form.status} onChange={e => set('status', e.target.value)} style={{ ...fld, cursor: 'pointer' }}>
          {['active','completed','cancelled'].map(s => <option key={s}>{s}</option>)}
        </select>
      </div>
      <div>
        <Label>Notes</Label>
        <textarea value={form.notes} onChange={e => set('notes', e.target.value)} rows={2} style={{ ...fld, resize: 'vertical' }} placeholder="Delivery address, access notes…" onFocus={e => e.target.style.borderColor='#4A9FD4'} onBlur={e => e.target.style.borderColor='#E2E8F0'} />
      </div>
      {error && <div style={{ background: '#FFF5F5', border: '1px solid #FEB2B2', borderRadius: '8px', padding: '10px 12px', fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#C53030' }}>{error}</div>}
      <button onClick={save} style={{ width: '100%', background: '#1B2A4A', color: '#fff', border: 'none', borderRadius: '8px', padding: '13px', cursor: 'pointer', fontFamily: 'Inter, sans-serif', fontSize: '15px', fontWeight: '700' }}>
        {rental ? 'Save Changes' : 'Create Rental'}
      </button>
    </div>
  );
};

// ── Rental Card (shared between admin + client views) ─────────────────────────
const RentalCard = ({ rental, isAdmin, onEdit }) => {
  const startDate = new Date(rental.start_date);
  const now = new Date();
  const monthsElapsed = Math.max(0, Math.floor((now - startDate) / (1000 * 60 * 60 * 24 * 30.44)));
  const buyoutAvailable = monthsElapsed >= 6;
  const buyoutCredit = Math.round(rental.monthly_rate * 0.5 * Math.max(0, monthsElapsed - 6));
  const salePrice = Number(rental.container_sale_price) || 0;
  const residual  = Number(rental.residual_value) || salePrice * 0.35;
  const rawBuyout = Math.max(residual, salePrice - buyoutCredit);
  const estimatedBuyout = Math.round(rawBuyout * 1.10); // + tax
  const progressPct = Math.min(100, (buyoutCredit / Math.max(1, salePrice - residual)) * 100);

  return (
    <div style={{ background: '#fff', borderRadius: '12px', border: '1px solid #E8EDF2', overflow: 'hidden' }}>
      {/* Header */}
      <div style={{ background: 'linear-gradient(135deg, #1B2A4A, #243a5e)', padding: '20px 24px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div>
          {isAdmin && <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '12px', color: 'rgba(255,255,255,0.5)', marginBottom: '4px' }}>{rental.customer_name}</div>}
          <div style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '24px', fontWeight: '800', color: '#fff' }}>{rental.container_type}</div>
          <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '13px', color: 'rgba(255,255,255,0.55)', marginTop: '2px' }}>
            Started {startDate.toLocaleDateString()} · Month {monthsElapsed}
          </div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '28px', fontWeight: '800', color: '#4A9FD4' }}>${rental.monthly_rate}<span style={{ fontSize: '14px', fontFamily: 'Inter, sans-serif', color: 'rgba(255,255,255,0.4)' }}>/mo</span></div>
          <span style={{ fontFamily: 'Inter, sans-serif', fontSize: '11px', fontWeight: '700', padding: '3px 10px', borderRadius: '100px', background: rental.status === 'active' ? 'rgba(56,161,105,0.25)' : 'rgba(255,255,255,0.1)', color: rental.status === 'active' ? '#9AE6B4' : 'rgba(255,255,255,0.4)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>
            {rental.status}
          </span>
        </div>
      </div>

      {/* Body */}
      <div style={{ padding: '20px 24px' }}>
        {/* Buyout progress bar */}
        {salePrice > 0 && (
          <div style={{ marginBottom: '20px' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
              <span style={{ fontFamily: 'Inter, sans-serif', fontSize: '13px', fontWeight: '600', color: '#1B2A4A' }}>Buyout Credit Progress</span>
              <span style={{ fontFamily: 'Inter, sans-serif', fontSize: '13px', fontWeight: '700', color: '#4A9FD4' }}>${buyoutCredit.toLocaleString()} credited</span>
            </div>
            <div style={{ background: '#EEF2F7', borderRadius: '100px', height: '8px', overflow: 'hidden' }}>
              <div style={{ width: `${progressPct}%`, height: '100%', background: 'linear-gradient(90deg, #4A9FD4, #1B2A4A)', borderRadius: '100px', transition: 'width 0.5s ease' }} />
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '4px' }}>
              <span style={{ fontFamily: 'Inter, sans-serif', fontSize: '11px', color: '#9AAAB8' }}>Start</span>
              <span style={{ fontFamily: 'Inter, sans-serif', fontSize: '11px', color: '#9AAAB8' }}>Residual ${residual.toLocaleString()}</span>
            </div>
          </div>
        )}

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '12px' }}>
          <div style={{ background: '#F4F6F8', borderRadius: '8px', padding: '14px', textAlign: 'center' }}>
            <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '11px', color: '#9AAAB8', fontWeight: '700', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: '4px' }}>Months Rented</div>
            <div style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '24px', fontWeight: '800', color: '#1B2A4A' }}>{monthsElapsed}</div>
          </div>
          <div style={{ background: buyoutAvailable ? 'rgba(74,159,212,0.08)' : '#F4F6F8', border: buyoutAvailable ? '1px solid rgba(74,159,212,0.2)' : '1px solid transparent', borderRadius: '8px', padding: '14px', textAlign: 'center' }}>
            <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '11px', color: '#9AAAB8', fontWeight: '700', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: '4px' }}>Buyout Option</div>
            <div style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '18px', fontWeight: '800', color: buyoutAvailable ? '#4A9FD4' : '#9AAAB8' }}>
              {buyoutAvailable ? `~$${estimatedBuyout.toLocaleString()}` : `Month ${6 - monthsElapsed} to go`}
            </div>
          </div>
          <div style={{ background: '#F4F6F8', borderRadius: '8px', padding: '14px', textAlign: 'center' }}>
            <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '11px', color: '#9AAAB8', fontWeight: '700', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: '4px' }}>Total Paid</div>
            <div style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '24px', fontWeight: '800', color: '#1B2A4A' }}>${(rental.monthly_rate * monthsElapsed).toLocaleString()}</div>
          </div>
        </div>

        {rental.notes && (
          <p style={{ fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#6B7E96', marginTop: '16px', padding: '12px', background: '#F9FAFB', borderRadius: '6px', lineHeight: '1.5' }}>
            📍 {rental.notes}
          </p>
        )}

        {isAdmin && (
          <button onClick={onEdit} style={{ marginTop: '16px', background: 'none', border: '1px solid #E2E8F0', borderRadius: '6px', padding: '8px 18px', cursor: 'pointer', fontFamily: 'Inter, sans-serif', fontSize: '13px', fontWeight: '600', color: '#4A9FD4' }}>
            Edit Rental
          </button>
        )}
      </div>
    </div>
  );
};

Object.assign(window, { AdminDashboard, Modal, RentalCard, QuoteEditForm, RentalEditForm });
