
// ── Client Dashboard ──────────────────────────────────────────────────────────
const ClientDashboard = ({ user, onSignOut, setCurrentPage }) => {
  const [activeTab, setActiveTab] = React.useState('rentals');
  const [quotes, setQuotes] = React.useState([]);
  const [rentals, setRentals] = React.useState([]);
  const [profile, setProfile] = React.useState({ full_name: user.full_name || '', phone: user.phone || '', email: user.email || '' });
  const [loading, setLoading] = React.useState(true);
  const [profileSaving, setProfileSaving] = React.useState(false);
  const [profileMsg, setProfileMsg] = React.useState('');

  React.useEffect(() => {
    (async () => {
      setLoading(true);
      if (SUPABASE_CONFIGURED) {
        try {
          await supa.claimCustomerRecords();
        } catch {}
        const [q, r] = await Promise.all([
          supa.getQuotes(user.id), supa.getRentals(user.id),
        ]);
        setQuotes(Array.isArray(q) ? q : []);
        setRentals(Array.isArray(r) ? r : []);
      } else {
        await new Promise(r => setTimeout(r, 400));
        setQuotes(MOCK_DATA.quotes.slice(0, 1));
        setRentals(MOCK_DATA.rentals);
      }
      setLoading(false);
    })();
  }, [user.id]);

  const saveProfile = async () => {
    setProfileSaving(true);
    if (SUPABASE_CONFIGURED) {
      await supa.update('profiles', { full_name: profile.full_name, phone: profile.phone }, `id=eq.${user.id}`);
    }
    await new Promise(r => setTimeout(r, 300));
    setProfileSaving(false);
    setProfileMsg('✓ Profile updated');
    setTimeout(() => setProfileMsg(''), 3000);
  };

  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>
  );

  const StatusBadge = ({ status }) => {
    const map = { pending: ['#FFF8E1','#856404'], quoted: ['#EBF8FF','#2B6CB0'], active: ['#F0FFF4','#276749'], completed: ['#F7FAFC','#4A5568'], cancelled: ['#FFF5F5','#C53030'] };
    const [bg, color] = map[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 inputStyle = { width: '100%', boxSizing: 'border-box', fontFamily: 'Inter, sans-serif', fontSize: '15px', fontWeight: '500', padding: '12px 14px', borderRadius: '8px', border: '1.5px solid #E2E8F0', color: '#1B2A4A', outline: 'none', transition: 'border-color 0.2s' };

  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 your portal…</p>
      </div>
      <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
    </div>
  );

  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' }}>MY PORTAL</span>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
          <button onClick={() => { setCurrentPage('home'); }} 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)'}>
            ← Back to Site
          </button>
          <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: '1000px', margin: '0 auto', padding: '32px' }}>
        {/* Welcome */}
        <div style={{ marginBottom: '28px' }}>
          <h1 style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '36px', fontWeight: '800', color: '#1B2A4A', margin: '0 0 4px 0' }}>
            Welcome back{profile.full_name ? `, ${profile.full_name.split(' ')[0]}` : ''}
          </h1>
          <p style={{ fontFamily: 'Inter, sans-serif', fontSize: '14px', color: '#6B7E96', margin: 0 }}>
            Manage your rentals, quotes, and account details.
          </p>
        </div>

        {/* Summary cards */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '16px', marginBottom: '28px' }}>
          {[
            { label: 'Active Rentals', value: rentals.filter(r => r.status === 'active').length, icon: '📦', color: '#4A9FD4' },
            { label: 'Saved Quotes', value: quotes.length, icon: '📋', color: '#1B2A4A' },
            { label: 'Buyout Available', value: rentals.filter(r => {
              const months = Math.floor((new Date() - new Date(r.start_date)) / (1000*60*60*24*30.44));
              return months >= 6 && r.status === 'active';
            }).length, icon: '🔓', color: '#38A169' },
          ].map(s => (
            <div key={s.label} style={{ background: '#fff', borderRadius: '10px', padding: '20px 24px', border: '1px solid #E8EDF2', display: 'flex', alignItems: 'center', gap: '16px' }}>
              <div style={{ fontSize: '28px' }}>{s.icon}</div>
              <div>
                <div style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '32px', fontWeight: '800', color: s.color, lineHeight: 1 }}>{s.value}</div>
                <div style={{ fontSize: '12px', color: '#6B7E96', fontWeight: '600', marginTop: '2px' }}>{s.label}</div>
              </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="rentals" label="📦 My Rentals" count={rentals.length} />
          <TabBtn id="quotes" label="📋 My Quotes" count={quotes.length} />
          <TabBtn id="profile" label="👤 Profile" />
        </div>

        {/* ── RENTALS ── */}
        {activeTab === 'rentals' && (
          <div>
            {rentals.length === 0 ? (
              <div style={{ background: '#fff', borderRadius: '12px', border: '1px solid #E8EDF2', padding: '60px 32px', textAlign: 'center' }}>
                <div style={{ fontSize: '48px', marginBottom: '16px' }}>📦</div>
                <h3 style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '24px', fontWeight: '700', color: '#1B2A4A', margin: '0 0 10px 0' }}>No active rentals</h3>
                <p style={{ fontFamily: 'Inter, sans-serif', fontSize: '14px', color: '#6B7E96', margin: '0 0 24px 0' }}>
                  Ready to start renting? Get a free quote and we'll set everything up for you.
                </p>
                <CTAButton variant="primary" onClick={() => setCurrentPage('rentals')}>View Rental Options →</CTAButton>
              </div>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
                {rentals.map(r => <RentalCard key={r.id} rental={r} isAdmin={false} />)}
                <div style={{ padding: '16px 20px', background: 'rgba(74,159,212,0.06)', border: '1px solid rgba(74,159,212,0.15)', borderRadius: '8px' }}>
                  <p style={{ fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#2E6FA3', margin: 0, lineHeight: '1.6' }}>
                    <strong>Questions about your rental or buyout?</strong> Call <a href="tel:2532719238" style={{ color: '#4A9FD4', fontWeight: '700' }}>(253) 271-9238</a> or email <a href="mailto:Sales@seasteelstorage.com" style={{ color: '#4A9FD4', fontWeight: '700' }}>Sales@seasteelstorage.com</a> — we'll pull up your current buyout price anytime.
                  </p>
                </div>
              </div>
            )}
          </div>
        )}

        {/* ── QUOTES ── */}
        {activeTab === 'quotes' && (
          <div>
            {quotes.length === 0 ? (
              <div style={{ background: '#fff', borderRadius: '12px', border: '1px solid #E8EDF2', padding: '60px 32px', textAlign: 'center' }}>
                <div style={{ fontSize: '48px', marginBottom: '16px' }}>📋</div>
                <h3 style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '24px', fontWeight: '700', color: '#1B2A4A', margin: '0 0 10px 0' }}>No saved quotes yet</h3>
                <p style={{ fontFamily: 'Inter, sans-serif', fontSize: '14px', color: '#6B7E96', margin: '0 0 24px 0' }}>
                  Submit a quote request and it'll show up here with status updates.
                </p>
                <CTAButton variant="primary" onClick={() => setCurrentPage('contact')}>Request a Quote →</CTAButton>
              </div>
            ) : (
              <div style={{ background: '#fff', borderRadius: '12px', border: '1px solid #E8EDF2', overflow: 'hidden' }}>
                {quotes.map((q, i) => (
                  <div key={q.id} style={{ padding: '20px 24px', borderBottom: i < quotes.length - 1 ? '1px solid #EEF2F7' : 'none', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: '16px' }}>
                    <div style={{ flex: 1 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: '10px', marginBottom: '6px' }}>
                        <span style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '18px', fontWeight: '700', color: '#1B2A4A' }}>
                          {q.interest === 'sale' ? 'Purchase' : q.interest === 'rental' ? 'Rental' : 'Inquiry'} — {q.size}
                        </span>
                        <StatusBadge status={q.status || 'pending'} />
                      </div>
                      <p style={{ fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#6B7E96', margin: '0 0 4px 0' }}>
                        {q.condition} · ZIP {q.zip} · Submitted {new Date(q.created_at).toLocaleDateString()}
                      </p>
                      {q.message && <p style={{ fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#4A5568', margin: '6px 0 0', fontStyle: 'italic' }}>"{q.message}"</p>}
                      {q.admin_notes && (
                        <div style={{ marginTop: '10px', padding: '10px 14px', background: '#EBF8FF', borderRadius: '6px', borderLeft: '3px solid #4A9FD4' }}>
                          <p style={{ fontFamily: 'Inter, sans-serif', fontSize: '13px', color: '#2B6CB0', margin: 0 }}>
                            <strong>From Sea Steel Storage:</strong> {q.admin_notes}
                          </p>
                        </div>
                      )}
                    </div>
                    {q.quoted_price && (
                      <div style={{ textAlign: 'right', flexShrink: 0 }}>
                        <div style={{ fontFamily: 'Inter, sans-serif', fontSize: '11px', color: '#9AAAB8', fontWeight: '700', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: '4px' }}>Quoted Price</div>
                        <div style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '28px', fontWeight: '800', color: '#4A9FD4' }}>${Number(q.quoted_price).toLocaleString()}</div>
                      </div>
                    )}
                  </div>
                ))}
              </div>
            )}
            <div style={{ marginTop: '16px', textAlign: 'right' }}>
              <CTAButton variant="navy" onClick={() => setCurrentPage('contact')}>+ New Quote Request</CTAButton>
            </div>
          </div>
        )}

        {/* ── PROFILE ── */}
        {activeTab === 'profile' && (
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '24px' }} className="profile-grid">
            <div style={{ background: '#fff', borderRadius: '12px', border: '1px solid #E8EDF2', padding: '28px' }}>
              <h3 style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '22px', fontWeight: '700', color: '#1B2A4A', margin: '0 0 24px 0' }}>Profile Details</h3>
              <div style={{ marginBottom: '16px' }}>
                <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Full Name</label>
                <input type="text" value={profile.full_name} onChange={e => setProfile(p => ({ ...p, full_name: e.target.value }))} style={inputStyle}
                  onFocus={e => e.target.style.borderColor = '#4A9FD4'}
                  onBlur={e => e.target.style.borderColor = '#E2E8F0'}
                  placeholder="Your name"
                />
              </div>
              <div style={{ marginBottom: '16px' }}>
                <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Email Address</label>
                <input type="email" value={profile.email} disabled style={{ ...inputStyle, background: '#F9FAFB', color: '#9AAAB8', cursor: 'not-allowed' }} />
                <p style={{ fontFamily: 'Inter, sans-serif', fontSize: '12px', color: '#9AAAB8', marginTop: '4px' }}>Email cannot be changed here. Contact support.</p>
              </div>
              <div style={{ marginBottom: '24px' }}>
                <label style={{ display: 'block', fontSize: '12px', fontWeight: '700', color: '#6B7E96', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: '6px' }}>Phone Number</label>
                <input type="tel" value={profile.phone} onChange={e => setProfile(p => ({ ...p, phone: e.target.value }))} style={inputStyle}
                  onFocus={e => e.target.style.borderColor = '#4A9FD4'}
                  onBlur={e => e.target.style.borderColor = '#E2E8F0'}
                  placeholder="(253) 555-0100"
                />
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: '14px' }}>
                <button onClick={saveProfile} disabled={profileSaving} style={{ background: profileSaving ? '#9AAAB8' : '#1B2A4A', color: '#fff', border: 'none', borderRadius: '8px', padding: '12px 28px', cursor: profileSaving ? 'not-allowed' : 'pointer', fontFamily: 'Inter, sans-serif', fontSize: '14px', fontWeight: '700', transition: 'background 0.2s' }}
                  onMouseEnter={e => { if (!profileSaving) e.target.style.background = '#4A9FD4'; }}
                  onMouseLeave={e => { if (!profileSaving) e.target.style.background = '#1B2A4A'; }}>
                  {profileSaving ? 'Saving…' : 'Save Changes'}
                </button>
                {profileMsg && <span style={{ fontFamily: 'Inter, sans-serif', fontSize: '14px', color: '#38A169', fontWeight: '600' }}>{profileMsg}</span>}
              </div>
            </div>

            {/* Account info */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
              <div style={{ background: '#fff', borderRadius: '12px', border: '1px solid #E8EDF2', padding: '24px' }}>
                <h3 style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '20px', fontWeight: '700', color: '#1B2A4A', margin: '0 0 16px 0' }}>Contact Sea Steel</h3>
                <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
                  <a href="tel:2532719238" style={{ display: 'flex', alignItems: 'center', gap: '10px', textDecoration: 'none', color: '#4A9FD4', fontFamily: 'Inter, sans-serif', fontSize: '14px', fontWeight: '600' }}>
                    📞 (253) 271-9238
                  </a>
                  <a href="mailto:Sales@seasteelstorage.com" style={{ display: 'flex', alignItems: 'center', gap: '10px', textDecoration: 'none', color: '#4A9FD4', fontFamily: 'Inter, sans-serif', fontSize: '14px', fontWeight: '600' }}>
                    ✉ Sales@seasteelstorage.com
                  </a>
                </div>
              </div>
              <div style={{ background: 'linear-gradient(135deg, #1B2A4A, #243a5e)', borderRadius: '12px', padding: '24px' }}>
                <h3 style={{ fontFamily: '"Barlow Condensed", sans-serif', fontSize: '20px', fontWeight: '700', color: '#fff', margin: '0 0 10px 0' }}>Need Something?</h3>
                <p style={{ fontFamily: 'Inter, sans-serif', fontSize: '13px', color: 'rgba(255,255,255,0.6)', lineHeight: '1.6', margin: '0 0 16px 0' }}>
                  Get pricing, check your buyout balance, or ask about delivery.
                </p>
                <CTAButton variant="primary" onClick={() => setCurrentPage('contact')}>Get a Quote</CTAButton>
              </div>
            </div>
          </div>
        )}
      </div>
      <style>{`@media (max-width: 768px) { .profile-grid { grid-template-columns: 1fr !important; } }`}</style>
    </div>
  );
};

Object.assign(window, { ClientDashboard });
