import { useState, useEffect, type FormEvent } from 'react';
import WatchlistItemCard, { type WatchlistItem } from './WatchlistItemCard';
import AdvancedSizesSection from './AdvancedSizesSection';

// ── Types ────────────────────────────────────────────────────────────────
interface UserProfile {
  id: string;
  email: string;
  first_name: string | null;
  last_name: string | null;
  shoe_size: string | null;
  gender_preference: string;
  alert_threshold_pct: number;
  alert_frequency: string;
  alert_day_of_week: string;
  notify_back_in_stock: boolean;
  notify_weekly_digest: boolean;
  notify_new_releases: boolean;
  paused_until: string | null;
  budget_max: number | null;
  email_verified: boolean;
}

// ── LoginForm ────────────────────────────────────────────────────────────
function LoginForm() {
  const [email, setEmail] = useState('');
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState('');

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setMessage('');
    try {
      const res = await fetch('/api/auth/register', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email }),
      });
      const data = await res.json();
      if (data.ok) {
        setMessage('Check je email voor de bevestigingslink!');
      } else if (data.error?.includes('al geregistreerd')) {
        const loginRes = await fetch('/api/auth/login', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ email }),
        });
        const loginData = await loginRes.json();
        setMessage(loginData.message || 'Check je email voor de inloglink!');
      } else {
        setMessage(data.error || 'Er ging iets mis');
      }
    } catch {
      setMessage('Er ging iets mis');
    }
    setLoading(false);
  };

  return (
    <div className="mx-auto max-w-md py-12">
      <div className="rounded-2xl border border-border/30 bg-bg-card p-8 text-center">
        <svg className="mx-auto mb-4 h-12 w-12 text-accent" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
          <path strokeLinecap="round" strokeLinejoin="round" d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z" />
        </svg>
        <h2 className="mb-2 text-xl font-bold text-text">Mijn Profiel</h2>
        <p className="mb-6 text-sm text-text-muted">
          Log in om je voorkeuren, watchlist en e-mailinstellingen te beheren.
        </p>
        {/* Google login */}
        <a
          href="/api/auth/google?return_to=/profiel"
          className="mb-4 flex w-full items-center justify-center gap-3 rounded-lg border border-border/50 bg-bg-elevated px-4 py-3 font-semibold text-text transition-all hover:border-accent/30 hover:bg-bg-elevated/80"
        >
          <svg viewBox="0 0 24 24" className="h-5 w-5" xmlns="http://www.w3.org/2000/svg">
            <path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4"/>
            <path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/>
            <path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05"/>
            <path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/>
          </svg>
          Inloggen met Google
        </a>

        <div className="relative mb-4">
          <div className="absolute inset-0 flex items-center"><div className="w-full border-t border-border/30"></div></div>
          <div className="relative flex justify-center"><span className="bg-bg-card px-3 text-xs text-text-muted">of via e-mail</span></div>
        </div>

        <form onSubmit={handleSubmit}>
          <input
            type="email"
            value={email}
            onChange={e => setEmail(e.target.value)}
            placeholder="je@email.nl"
            required
            className="mb-3 w-full rounded-lg border border-border/30 bg-bg-elevated px-4 py-3 text-text placeholder-text-muted focus:border-accent/50 focus:outline-none"
          />
          {message && (
            <p className={`mb-3 text-sm ${message.includes('Check') ? 'text-accent' : 'text-red-400'}`}>
              {message}
            </p>
          )}
          <button
            type="submit"
            disabled={loading}
            className="w-full rounded-lg bg-accent px-4 py-3 font-bold text-bg transition-colors hover:bg-accent-dim disabled:opacity-50"
          >
            {loading ? 'Even geduld...' : 'Stuur magic link'}
          </button>
        </form>
        <p className="mt-4 text-xs text-text-muted">
          Via e-mail ontvang je een magic link — geen wachtwoord nodig.
        </p>
      </div>
    </div>
  );
}

// ── Tabs ──────────────────────────────────────────────────────────────────
const TABS = [
  { id: 'profiel', label: 'Profiel', icon: 'M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z' },
  { id: 'watchlist', label: 'Watchlist', icon: 'M21 8.25c0-2.485-2.099-4.5-4.688-4.5-1.935 0-3.597 1.126-4.312 2.733-.715-1.607-2.377-2.733-4.313-2.733C5.1 3.75 3 5.765 3 8.25c0 7.22 9 12 9 12s9-4.78 9-12z' },
  { id: 'email', label: 'E-mail', icon: 'M21.75 6.75v10.5a2.25 2.25 0 01-2.25 2.25h-15a2.25 2.25 0 01-2.25-2.25V6.75m19.5 0A2.25 2.25 0 0019.5 4.5h-15a2.25 2.25 0 00-2.25 2.25m19.5 0v.243a2.25 2.25 0 01-1.07 1.916l-7.5 4.615a2.25 2.25 0 01-2.36 0L3.32 8.91a2.25 2.25 0 01-1.07-1.916V6.75' },
] as const;

type TabId = typeof TABS[number]['id'];

const SIZES = ['35', '36', '36.5', '37', '37.5', '38', '38.5', '39', '39.5', '40', '40.5', '41', '41.5', '42', '42.5', '43', '43.5', '44', '44.5', '45', '45.5', '46', '46.5', '47', '47.5', '48', '49', '50'];

const WEEKDAYS = [
  { value: 'monday', short: 'Ma' },
  { value: 'tuesday', short: 'Di' },
  { value: 'wednesday', short: 'Wo' },
  { value: 'thursday', short: 'Do' },
  { value: 'friday', short: 'Vr' },
  { value: 'saturday', short: 'Za' },
  { value: 'sunday', short: 'Zo' },
];

// ── Toast helper ─────────────────────────────────────────────────────────
function showToast(msg: string, type: 'success' | 'info' | 'error' = 'success') {
  if (typeof window !== 'undefined' && (window as any).__showToast) {
    (window as any).__showToast(msg, type);
  }
}

// ── Main Component ───────────────────────────────────────────────────────
export default function ProfielApp() {
  const [user, setUser] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [tab, setTab] = useState<TabId>('profiel');

  // Profile state
  const [profile, setProfile] = useState<UserProfile | null>(null);
  const [saving, setSaving] = useState(false);

  // Watchlist state
  const [watchlist, setWatchlist] = useState<WatchlistItem[]>([]);

  useEffect(() => {
    fetch('/api/auth/session')
      .then(r => r.json())
      .then(data => {
        setUser(data.user);
        if (data.user) {
          loadAllData();
        }
        setLoading(false);
      })
      .catch(() => setLoading(false));
  }, []);

  async function loadAllData() {
    const [profileRes, watchlistRes] = await Promise.all([
      fetch('/api/user/profile', { credentials: 'include' }).then(r => r.json()).catch(() => null),
      fetch('/api/watchlist', { credentials: 'include' }).then(r => r.json()).catch(() => ({ items: [] })),
    ]);
    if (profileRes && !profileRes.error) setProfile(profileRes);
    setWatchlist(watchlistRes.items || []);
  }

  if (loading) return <div className="py-12 text-center text-text-muted">Laden...</div>;
  if (!user) return <LoginForm />;

  // ── Tab Navigation ───────────────────────────────────────────────────
  return (
    <div>
      {/* Tab bar */}
      <div className="mb-8 flex gap-1 overflow-x-auto rounded-xl border border-border/30 bg-bg-card p-1">
        {TABS.map(t => (
          <button
            key={t.id}
            onClick={() => setTab(t.id)}
            className={`flex flex-1 items-center justify-center gap-2 whitespace-nowrap rounded-lg px-4 py-2.5 text-sm font-semibold transition-all ${
              tab === t.id
                ? 'bg-accent text-bg'
                : 'text-text-muted hover:bg-bg-elevated hover:text-text'
            }`}
          >
            <svg className="h-4 w-4 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d={t.icon} />
            </svg>
            <span className="hidden sm:inline">{t.label}</span>
          </button>
        ))}
      </div>

      {/* Tab content */}
      {tab === 'profiel' && <ProfileTab profile={profile} setProfile={setProfile} saving={saving} setSaving={setSaving} />}
      {tab === 'watchlist' && (
        <WatchlistTab
          items={watchlist}
          setItems={setWatchlist}
        />
      )}
      {tab === 'email' && <EmailTab profile={profile} setProfile={setProfile} />}
    </div>
  );
}

// ── Tab 1: Profiel ───────────────────────────────────────────────────────
function ProfileTab({ profile, setProfile, saving, setSaving }: {
  profile: UserProfile | null;
  setProfile: (p: UserProfile) => void;
  saving: boolean;
  setSaving: (s: boolean) => void;
}) {
  const [firstName, setFirstName] = useState(profile?.first_name || '');
  const [lastName, setLastName] = useState(profile?.last_name || '');
  const [shoeSize, setShoeSize] = useState(profile?.shoe_size || '');
  const [gender, setGender] = useState(profile?.gender_preference || 'all');
  const [budgetMax, setBudgetMax] = useState(profile?.budget_max?.toString() || '');

  // Sync state when profile loads asynchronously
  useEffect(() => {
    if (profile) {
      setFirstName(profile.first_name || '');
      setLastName(profile.last_name || '');
      setShoeSize(profile.shoe_size || '');
      setGender(profile.gender_preference || 'all');
      setBudgetMax(profile.budget_max?.toString() || '');
    }
  }, [profile]);

  const handleSave = async () => {
    setSaving(true);
    const body: Record<string, unknown> = {
      first_name: firstName || null,
      last_name: lastName || null,
      shoe_size: shoeSize || null,
      gender_preference: gender,
      budget_max: budgetMax ? parseInt(budgetMax) : null,
    };
    const res = await fetch('/api/user/profile', {
      method: 'PATCH',
      credentials: 'include',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body),
    });
    if (res.ok) {
      setProfile({ ...profile!, ...body } as UserProfile);
      showToast('Profiel opgeslagen', 'success');
    } else {
      showToast('Opslaan mislukt', 'error');
    }
    setSaving(false);
  };

  const needsCompletion = !firstName || !shoeSize;

  return (
    <div className="space-y-6">
      {needsCompletion && (
        <div className="rounded-xl border border-accent/30 bg-accent/10 p-4">
          <p className="font-semibold text-accent">Stel je profiel in</p>
          <p className="text-sm text-text-muted">Voeg je naam en maat toe voor gepersonaliseerde alerts.</p>
        </div>
      )}

      <div className="rounded-2xl border border-border/30 bg-bg-card p-6">
        <h2 className="mb-4 text-lg font-bold text-text">Persoonlijke gegevens</h2>
        <div className="grid gap-4 sm:grid-cols-2">
          {/* First name */}
          <div>
            <label className="mb-1 block text-sm font-medium text-text-muted">Voornaam</label>
            <input
              type="text"
              value={firstName}
              onChange={e => setFirstName(e.target.value)}
              placeholder="Je voornaam (optioneel)"
              className="w-full rounded-lg border border-border/30 bg-bg-elevated px-3 py-2.5 text-text placeholder-text-muted focus:border-accent/50 focus:outline-none"
            />
          </div>

          {/* Last name */}
          <div>
            <label className="mb-1 block text-sm font-medium text-text-muted">Achternaam</label>
            <input
              type="text"
              value={lastName}
              onChange={e => setLastName(e.target.value)}
              placeholder="Je achternaam (optioneel)"
              className="w-full rounded-lg border border-border/30 bg-bg-elevated px-3 py-2.5 text-text placeholder-text-muted focus:border-accent/50 focus:outline-none"
            />
          </div>

          {/* Email (readonly) */}
          <div>
            <label className="mb-1 block text-sm font-medium text-text-muted">E-mailadres</label>
            <input
              type="email"
              value={profile?.email || ''}
              readOnly
              className="w-full rounded-lg border border-border/30 bg-bg-elevated/50 px-3 py-2.5 text-text-muted cursor-not-allowed"
            />
          </div>

          {/* Shoe size */}
          <div>
            <label className="mb-1 block text-sm font-medium text-text-muted">Schoenmaat</label>
            <select
              value={shoeSize}
              onChange={e => setShoeSize(e.target.value)}
              className="w-full rounded-lg border border-border/30 bg-bg-elevated px-3 py-2.5 text-text focus:border-accent/50 focus:outline-none"
            >
              <option value="">Selecteer maat</option>
              {SIZES.map(s => (
                <option key={s} value={s}>{s}</option>
              ))}
            </select>
          </div>

          {/* Gender */}
          <div>
            <label className="mb-1 block text-sm font-medium text-text-muted">Voorkeur</label>
            <div className="flex gap-2">
              {[
                { value: 'all', label: 'Alles' },
                { value: 'heren', label: 'Heren' },
                { value: 'dames', label: 'Dames' },
              ].map(opt => (
                <button
                  key={opt.value}
                  onClick={() => setGender(opt.value)}
                  className={`flex-1 rounded-lg border px-3 py-2.5 text-sm font-medium transition-all ${
                    gender === opt.value
                      ? 'border-accent bg-accent/10 text-accent'
                      : 'border-border/30 text-text-muted hover:border-accent/30'
                  }`}
                >
                  {opt.label}
                </button>
              ))}
            </div>
          </div>

          {/* Budget max */}
          <div className="sm:col-span-2">
            <label className="mb-1 block text-sm font-medium text-text-muted">Max budget voor alerts</label>
            <div className="relative">
              <span className="absolute left-3 top-1/2 -translate-y-1/2 text-text-muted">€</span>
              <input
                type="number"
                value={budgetMax}
                onChange={e => setBudgetMax(e.target.value)}
                placeholder="Geen limiet"
                min="0"
                step="10"
                className="w-full rounded-lg border border-border/30 bg-bg-elevated pl-7 pr-3 py-2.5 text-text placeholder-text-muted focus:border-accent/50 focus:outline-none"
              />
            </div>
            <p className="mt-1 text-xs text-text-muted">Ontvang alleen alerts voor sneakers onder dit bedrag</p>
          </div>
        </div>

        <button
          onClick={handleSave}
          disabled={saving}
          className="mt-6 rounded-lg bg-accent px-6 py-2.5 font-bold text-bg transition-all hover:shadow-lg hover:shadow-accent/20 disabled:opacity-50"
        >
          {saving ? 'Opslaan...' : 'Opslaan'}
        </button>
      </div>

      <AdvancedSizesSection />
      <TasteProfileSection />

      {/* Logout button */}
      <div className="mt-12 pt-6 border-t border-border/30">
        <button
          onClick={async () => {
            await fetch('/api/auth/logout', { method: 'POST', credentials: 'include' });
            window.location.href = '/';
          }}
          className="text-sm text-text-muted hover:text-red-400 transition-colors"
        >
          Uitloggen
        </button>
      </div>
    </div>
  );
}

// ── Taste Profile Section ────────────────────────────────────────────────
function TasteProfileSection() {
  const [profile, setProfile] = useState<{
    preferred_brands: { slug: string; name: string; score: number }[];
    preferred_price_range: { min: number | null; max: number | null; avg: number | null };
  } | null>(null);

  useEffect(() => {
    fetch('/api/user/taste-profile', { credentials: 'include' })
      .then(r => r.json())
      .then(data => {
        if (!data.error) setProfile(data);
      })
      .catch(() => {});
  }, []);

  if (!profile || profile.preferred_brands.length === 0) return null;

  const maxScore = Math.max(...profile.preferred_brands.map(b => b.score));

  return (
    <div className="mt-6 rounded-2xl border border-border/30 bg-bg-card p-6">
      <h2 className="mb-1 text-lg font-bold text-text">Jouw smaakprofiel</h2>
      <p className="mb-4 text-xs text-text-muted">Gebaseerd op je watchlist en gevolgde merken</p>

      {/* Brand preferences */}
      <div className="space-y-2">
        {profile.preferred_brands.slice(0, 5).map(brand => (
          <div key={brand.slug} className="flex items-center gap-3">
            <span className="w-24 text-sm font-medium text-text truncate">{brand.name}</span>
            <div className="flex-1 h-4 rounded-full bg-bg-elevated overflow-hidden">
              <div
                className="h-full rounded-full bg-accent/60"
                style={{ width: `${(brand.score / maxScore) * 100}%` }}
              />
            </div>
          </div>
        ))}
      </div>

      {/* Price range */}
      {profile.preferred_price_range.avg && (
        <div className="mt-4 flex gap-4 text-sm">
          <div className="rounded-lg border border-border/20 bg-bg-elevated px-3 py-2">
            <p className="text-[10px] text-text-muted uppercase tracking-wider">Gem. prijs</p>
            <p className="font-bold text-accent">&euro;{profile.preferred_price_range.avg}</p>
          </div>
          {profile.preferred_price_range.min && (
            <div className="rounded-lg border border-border/20 bg-bg-elevated px-3 py-2">
              <p className="text-[10px] text-text-muted uppercase tracking-wider">Bereik</p>
              <p className="font-bold text-text">
                &euro;{profile.preferred_price_range.min} – &euro;{profile.preferred_price_range.max}
              </p>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

// ── Tab 2: Watchlist ─────────────────────────────────────────────────────
type SortOption = 'newest' | 'price_low' | 'price_high' | 'discount' | 'price_drop';

function WatchlistTab({ items, setItems }: {
  items: WatchlistItem[];
  setItems: (items: WatchlistItem[]) => void;
}) {
  const [sortBy, setSortBy] = useState<SortOption>('newest');
  const [filterBrand, setFilterBrand] = useState<string>('all');
  const [filterDealsOnly, setFilterDealsOnly] = useState(false);

  const removeItem = async (productId: number) => {
    await fetch('/api/watchlist', {
      method: 'DELETE',
      credentials: 'include',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ product_id: productId }),
    });
    setItems(items.filter(i => i.product_id !== productId));
    showToast('Verwijderd van watchlist', 'success');
  };

  const updateTargetPrice = async (productId: number, price: number | null) => {
    await fetch('/api/watchlist', {
      method: 'PUT',
      credentials: 'include',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ product_id: productId, target_price: price }),
    });
    setItems(items.map(i => i.product_id === productId ? { ...i, target_price: price } : i));
    showToast('Doelprijs bijgewerkt', 'success');
  };

  const toggleNotification = async (productId: number, field: 'notify_price_drop' | 'notify_back_in_stock' | 'notify_push_price_drop' | 'notify_push_back_in_stock', value: boolean) => {
    await fetch('/api/watchlist', {
      method: 'PUT',
      credentials: 'include',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ product_id: productId, [field]: value }),
    });
    setItems(items.map(i => i.product_id === productId ? { ...i, [field]: value } : i));
    showToast(value ? 'Melding ingeschakeld' : 'Melding uitgeschakeld', 'success');
  };

  const updateSizeOverride = async (productId: number, sizeOverride: string | null) => {
    await fetch('/api/watchlist', {
      method: 'PUT',
      credentials: 'include',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ product_id: productId, size_override: sizeOverride }),
    });
    setItems(items.map(i => i.product_id === productId ? { ...i, size_override: sizeOverride } : i));
    showToast('Maat bijgewerkt', 'success');
  };

  // Derive unique brands
  const brands = [...new Set(items.map(i => i.brand))].sort();

  // Filter
  let filtered = items;
  if (filterBrand !== 'all') {
    filtered = filtered.filter(i => i.brand === filterBrand);
  }
  if (filterDealsOnly) {
    filtered = filtered.filter(i => {
      const lp = i.lowest_price ? parseFloat(String(i.lowest_price)) : null;
      const tp = i.target_price ? parseFloat(String(i.target_price)) : null;
      return lp && tp && lp <= tp;
    });
  }

  // Sort
  const sorted = [...filtered].sort((a, b) => {
    const aPrice = a.lowest_price ? parseFloat(String(a.lowest_price)) : Infinity;
    const bPrice = b.lowest_price ? parseFloat(String(b.lowest_price)) : Infinity;
    const aOrig = a.original_price ? parseFloat(String(a.original_price)) : aPrice;
    const bOrig = b.original_price ? parseFloat(String(b.original_price)) : bPrice;
    const aDiscount = aOrig > 0 ? (aOrig - aPrice) / aOrig : 0;
    const bDiscount = bOrig > 0 ? (bOrig - bPrice) / bOrig : 0;

    switch (sortBy) {
      case 'price_low': return aPrice - bPrice;
      case 'price_high': return bPrice - aPrice;
      case 'discount': return bDiscount - aDiscount;
      case 'price_drop': {
        const aDelta = (a.price_7d_ago && a.lowest_price) ? parseFloat(String(a.lowest_price)) - parseFloat(String(a.price_7d_ago)) : 0;
        const bDelta = (b.price_7d_ago && b.lowest_price) ? parseFloat(String(b.lowest_price)) - parseFloat(String(b.price_7d_ago)) : 0;
        return aDelta - bDelta;
      }
      default: return 0;
    }
  });

  if (items.length === 0) {
    return (
      <div className="rounded-2xl border border-border/30 bg-bg-card p-8 text-center">
        <svg className="mx-auto mb-4 h-12 w-12 text-text-muted" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
          <path strokeLinecap="round" strokeLinejoin="round" d="M21 8.25c0-2.485-2.099-4.5-4.688-4.5-1.935 0-3.597 1.126-4.312 2.733-.715-1.607-2.377-2.733-4.313-2.733C5.1 3.75 3 5.765 3 8.25c0 7.22 9 12 9 12s9-4.78 9-12z" />
        </svg>
        <p className="text-text-muted mb-4">Je watchlist is nog leeg</p>
        <a href="/" className="inline-block rounded-lg bg-accent px-6 py-2.5 font-bold text-bg">
          Ontdek sneakers
        </a>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {/* Sort & Filter controls */}
      <div className="flex flex-wrap items-center gap-3">
        <p className="text-sm text-text-muted">{filtered.length} sneaker{filtered.length !== 1 ? 's' : ''}</p>
        <div className="ml-auto flex flex-wrap items-center gap-2">
          {brands.length > 1 && (
            <select
              value={filterBrand}
              onChange={e => setFilterBrand(e.target.value)}
              className="rounded-lg border border-border/30 bg-bg-elevated px-2 py-1.5 text-xs text-text focus:border-accent/50 focus:outline-none"
            >
              <option value="all">Alle merken</option>
              {brands.map(b => <option key={b} value={b}>{b}</option>)}
            </select>
          )}
          <select
            value={sortBy}
            onChange={e => setSortBy(e.target.value as SortOption)}
            className="rounded-lg border border-border/30 bg-bg-elevated px-2 py-1.5 text-xs text-text focus:border-accent/50 focus:outline-none"
          >
            <option value="newest">Nieuwste eerst</option>
            <option value="price_low">Laagste prijs</option>
            <option value="price_high">Hoogste prijs</option>
            <option value="discount">Hoogste korting</option>
            <option value="price_drop">Grootste prijsdaling</option>
          </select>
          <label className="flex items-center gap-1.5 cursor-pointer">
            <input
              type="checkbox"
              checked={filterDealsOnly}
              onChange={e => setFilterDealsOnly(e.target.checked)}
              className="rounded border-border/30 accent-accent"
            />
            <span className="text-xs text-text-muted">Alleen deals</span>
          </label>
        </div>
      </div>

      {sorted.length === 0 ? (
        <div className="rounded-xl border border-border/30 bg-bg-card p-8 text-center">
          <p className="text-text-muted">Geen sneakers gevonden met deze filters</p>
        </div>
      ) : (
        sorted.map(item => (
          <WatchlistItemCard
            key={item.id}
            item={item}
            onRemove={removeItem}
            onUpdateTargetPrice={updateTargetPrice}
            onToggleNotification={toggleNotification}
            onUpdateSizeOverride={updateSizeOverride}
            pushEnabled={typeof window !== 'undefined' && localStorage.getItem('sp_push_subscribed') === '1'}
            onEnablePush={() => {}}
          />
        ))
      )}
    </div>
  );
}

// ── Tab 3: Email Preferences ─────────────────────────────────────────────
function EmailTab({ profile, setProfile }: {
  profile: UserProfile | null;
  setProfile: (p: UserProfile) => void;
}) {
  const [threshold, setThreshold] = useState(profile?.alert_threshold_pct || 15);
  const [frequency, setFrequency] = useState(profile?.alert_frequency || 'instant');
  const [alertDay, setAlertDay] = useState(profile?.alert_day_of_week || 'monday');
  const [notifyBIS, setNotifyBIS] = useState(profile?.notify_back_in_stock ?? true);
  const [notifyDigest, setNotifyDigest] = useState(profile?.notify_weekly_digest ?? true);
  const [notifyReleases, setNotifyReleases] = useState(profile?.notify_new_releases ?? false);
  const [saving, setSaving] = useState(false);
  const [pausing, setPausing] = useState(false);
  const [pushEnabled, setPushEnabled] = useState(false);
  const [pushSubscribing, setPushSubscribing] = useState(false);

  const pausedUntil = profile?.paused_until ? new Date(profile.paused_until) : null;
  const isPaused = pausedUntil && pausedUntil > new Date();

  // Check push notification status on mount
  useEffect(() => {
    setPushEnabled(localStorage.getItem('sp_push_subscribed') === '1');
  }, []);

  const enablePush = async () => {
    if (!('PushManager' in window) || !('serviceWorker' in navigator)) {
      showToast('Je browser ondersteunt geen push notificaties.', 'error');
      return;
    }
    setPushSubscribing(true);
    try {
      const reg = await navigator.serviceWorker.ready;
      const vapidKey = (import.meta as any).env?.PUBLIC_VAPID_KEY;
      const urlBase64ToUint8Array = (base64String: string) => {
        const padding = '='.repeat((4 - (base64String.length % 4)) % 4);
        const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
        const rawData = atob(base64);
        const outputArray = new Uint8Array(rawData.length);
        for (let i = 0; i < rawData.length; ++i) outputArray[i] = rawData.charCodeAt(i);
        return outputArray;
      };
      const sub = await reg.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: urlBase64ToUint8Array(vapidKey),
      });
      await fetch('/api/push/subscribe', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify(sub.toJSON()),
      });
      localStorage.setItem('sp_push_subscribed', '1');
      localStorage.removeItem('sp_push_dismissed');
      setPushEnabled(true);
      showToast('Push notificaties ingeschakeld!', 'success');
    } catch (err: any) {
      showToast('Push notificaties konden niet worden ingeschakeld.', 'error');
    }
    setPushSubscribing(false);
  };

  const disablePush = async () => {
    setPushSubscribing(true);
    try {
      await fetch('/api/push/unsubscribe', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
      });
      localStorage.removeItem('sp_push_subscribed');
      setPushEnabled(false);
      showToast('Push notificaties uitgeschakeld', 'success');
    } catch (err) {
      showToast('Uitschakelen mislukt', 'error');
    }
    setPushSubscribing(false);
  };

  const savePreferences = async () => {
    setSaving(true);
    const body = {
      alert_threshold_pct: threshold,
      alert_frequency: frequency,
      alert_day_of_week: alertDay,
      notify_back_in_stock: notifyBIS,
      notify_weekly_digest: notifyDigest,
      notify_new_releases: notifyReleases,
    };
    const res = await fetch('/api/user/profile', {
      method: 'PATCH',
      credentials: 'include',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body),
    });
    if (res.ok) {
      setProfile({ ...profile!, ...body });
      showToast('E-mailvoorkeuren opgeslagen', 'success');
    } else {
      showToast('Opslaan mislukt', 'error');
    }
    setSaving(false);
  };

  const pauseEmails = async (days: number) => {
    setPausing(true);
    const res = await fetch('/api/user/pause', {
      method: 'POST',
      credentials: 'include',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ days }),
    });
    if (res.ok) {
      const data = await res.json();
      setProfile({ ...profile!, paused_until: data.paused_until });
      showToast(`E-mails gepauzeerd voor ${days} dagen`, 'success');
    }
    setPausing(false);
  };

  const resumeEmails = async () => {
    setPausing(true);
    const res = await fetch('/api/user/pause', { method: 'DELETE', credentials: 'include' });
    if (res.ok) {
      setProfile({ ...profile!, paused_until: null });
      showToast('E-mails hervat', 'success');
    }
    setPausing(false);
  };

  const thresholdLabels: Record<number, string> = {
    5: 'Elke daling',
    10: 'Kleine korting',
    15: 'Goede deals',
    20: 'Goede deals',
    25: 'Flinke korting',
    30: 'Top deals',
    35: 'Top deals',
    40: 'Mega sale',
    45: 'Mega sale',
    50: 'Mega sale',
  };

  const frequencyOptions = [
    { value: 'instant', label: 'Direct', desc: 'Zodra prijs daalt', icon: 'M3.75 13.5l10.5-11.25L12 10.5h8.25L9.75 21.75 12 13.5H3.75z' },
    { value: 'morning', label: 'Ochtend', desc: 'Dagelijks 08:00', icon: 'M12 3v2.25m6.364.386l-1.591 1.591M21 12h-2.25m-.386 6.364l-1.591-1.591M12 18.75V21m-4.773-4.227l-1.591 1.591M5.25 12H3m4.227-4.773L5.636 5.636M15.75 12a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0z' },
    { value: 'evening', label: 'Avond', desc: 'Dagelijks 19:00', icon: 'M21.752 15.002A9.718 9.718 0 0118 15.75c-5.385 0-9.75-4.365-9.75-9.75 0-1.33.266-2.597.748-3.752A9.753 9.753 0 003 11.25C3 16.635 7.365 21 12.75 21a9.753 9.753 0 009.002-5.998z' },
    { value: 'weekly', label: 'Wekelijks', desc: 'Maandag ochtend', icon: 'M6.75 3v2.25M17.25 3v2.25M3 18.75V7.5a2.25 2.25 0 012.25-2.25h13.5A2.25 2.25 0 0121 7.5v11.25m-18 0A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75m-18 0v-7.5A2.25 2.25 0 015.25 9h13.5A2.25 2.25 0 0121 11.25v7.5' },
  ];

  return (
    <div className="space-y-6">
      {/* Pause banner */}
      {isPaused && (
        <div className="flex items-center justify-between rounded-xl border border-yellow-500/30 bg-yellow-500/10 p-4">
          <div>
            <p className="font-semibold text-yellow-400">E-mails gepauzeerd</p>
            <p className="text-sm text-text-muted">
              Tot {pausedUntil!.toLocaleDateString('nl-NL', { day: 'numeric', month: 'long', year: 'numeric' })}
              . Watchlist-alerts komen nog steeds door.
            </p>
          </div>
          <button
            onClick={resumeEmails}
            disabled={pausing}
            className="shrink-0 rounded-lg border border-yellow-500/30 px-4 py-2 text-sm font-bold text-yellow-400 hover:bg-yellow-500/10 disabled:opacity-50"
          >
            Hervat
          </button>
        </div>
      )}

      {/* Alert threshold */}
      <div className="rounded-2xl border border-border/30 bg-bg-card p-6">
        <h2 className="mb-1 text-lg font-bold text-text">Alertgevoeligheid</h2>
        <p className="mb-4 text-sm text-text-muted">Vanaf welk kortingspercentage wil je een melding?</p>
        <div className="space-y-3">
          <input
            type="range"
            min="5"
            max="50"
            step="5"
            value={threshold}
            onChange={e => setThreshold(parseInt(e.target.value))}
            className="w-full accent-accent"
          />
          <div className="flex justify-between text-xs text-text-muted">
            <span>Elke daling</span>
            <span>Goede deals</span>
            <span>Top deals</span>
            <span>Mega sale</span>
          </div>
          <p className="text-center text-sm font-bold text-accent">
            {threshold}% — {thresholdLabels[threshold] || 'Goede deals'}
          </p>
        </div>
      </div>

      {/* Frequency */}
      <div className="rounded-2xl border border-border/30 bg-bg-card p-6">
        <h2 className="mb-1 text-lg font-bold text-text">Timing</h2>
        <p className="mb-4 text-sm text-text-muted">Wanneer wil je meldingen ontvangen?</p>
        <div className="grid grid-cols-2 gap-2 sm:grid-cols-4">
          {frequencyOptions.map(opt => (
            <button
              key={opt.value}
              onClick={() => setFrequency(opt.value)}
              className={`flex flex-col items-center gap-2 rounded-xl border p-4 transition-all ${
                frequency === opt.value
                  ? 'border-accent bg-accent/10 text-accent'
                  : 'border-border/30 text-text-muted hover:border-accent/30'
              }`}
            >
              <svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                <path strokeLinecap="round" strokeLinejoin="round" d={opt.icon} />
              </svg>
              <span className="text-sm font-bold">{opt.label}</span>
              <span className="text-[10px]">{opt.desc}</span>
            </button>
          ))}
        </div>
      </div>

      {/* Weekly day picker */}
      {frequency === 'weekly' && (
        <div className="rounded-2xl border border-border/30 bg-bg-card p-6">
          <h2 className="mb-1 text-lg font-bold text-text">Dag van de week</h2>
          <p className="mb-4 text-sm text-text-muted">Op welke dag wil je de wekelijkse digest ontvangen?</p>
          <div className="flex gap-2 flex-wrap">
            {WEEKDAYS.map(day => (
              <button
                key={day.value}
                onClick={() => setAlertDay(day.value)}
                className={`flex-1 min-w-[2.5rem] rounded-lg border px-2 py-2 text-sm font-medium transition-all ${
                  alertDay === day.value
                    ? 'border-accent bg-accent/10 text-accent'
                    : 'border-border/30 text-text-muted hover:border-accent/30'
                }`}
              >
                {day.short}
              </button>
            ))}
          </div>
        </div>
      )}

      {/* Notification types */}
      <div className="rounded-2xl border border-border/30 bg-bg-card p-6">
        <h2 className="mb-4 text-lg font-bold text-text">E-mail meldingen</h2>
        <div className="space-y-3">
          <label className="flex items-center justify-between gap-4 rounded-xl border border-border/20 bg-bg-elevated p-4 cursor-pointer">
            <div>
              <p className="font-medium text-text">Prijsdaling op watchlist</p>
              <p className="text-xs text-text-muted">Altijd aan — alleen de drempel is aanpasbaar</p>
            </div>
            <div className="h-6 w-10 rounded-full bg-accent/30 p-0.5 cursor-not-allowed">
              <div className="h-5 w-5 translate-x-4 rounded-full bg-accent"></div>
            </div>
          </label>

          <ToggleRow
            label="Back in stock"
            desc="Melding wanneer een sneaker van je watchlist weer beschikbaar is"
            checked={notifyBIS}
            onChange={setNotifyBIS}
          />
          <ToggleRow
            label="Wekelijkse deals digest"
            desc="Elke maandag een overzicht van de beste deals"
            checked={notifyDigest}
            onChange={setNotifyDigest}
          />
          <ToggleRow
            label="Nieuwe releases"
            desc="Meldingen over nieuwe sneakers van gevolgde merken"
            checked={notifyReleases}
            onChange={setNotifyReleases}
          />
        </div>
      </div>

      {/* Push notifications */}
      {('PushManager' in window) && (
        <div className="rounded-2xl border border-border/30 bg-bg-card p-6">
          <h2 className="mb-4 text-lg font-bold text-text">Push notificaties</h2>
          <p className="mb-4 text-sm text-text-muted">
            Ontvang directe browsernotificaties voor prijsdalingen op je watchlist items.
          </p>
          <div className="rounded-xl border border-border/20 bg-bg-elevated p-4">
            <div className="flex items-center justify-between gap-4">
              <div>
                <p className="font-medium text-text">
                  {pushEnabled ? '✓ Push notificaties actief' : 'Push notificaties'}
                </p>
                <p className="text-xs text-text-muted">
                  {pushEnabled
                    ? 'Je ontvangt direct een melding bij prijsdalingen'
                    : 'Inschakelen voor directe browsernotificaties'}
                </p>
              </div>
              <button
                onClick={pushEnabled ? disablePush : enablePush}
                disabled={pushSubscribing}
                className={`shrink-0 rounded-lg px-4 py-2 text-sm font-bold transition-all ${
                  pushEnabled
                    ? 'border border-border/30 text-text-muted hover:text-text'
                    : 'bg-accent text-bg hover:shadow-lg hover:shadow-accent/20'
                } disabled:opacity-50`}
              >
                {pushSubscribing ? 'Even geduld...' : pushEnabled ? 'Uitschakelen' : 'Inschakelen'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Save button */}
      <button
        onClick={savePreferences}
        disabled={saving}
        className="w-full rounded-lg bg-accent px-6 py-3 font-bold text-bg transition-all hover:shadow-lg hover:shadow-accent/20 disabled:opacity-50"
      >
        {saving ? 'Opslaan...' : 'Voorkeuren opslaan'}
      </button>

      {/* Smart pause */}
      {!isPaused && (
        <div className="rounded-2xl border border-border/30 bg-bg-card p-6">
          <h2 className="mb-1 text-lg font-bold text-text">Even pauze?</h2>
          <p className="mb-4 text-sm text-text-muted">Pauzeer marketing e-mails tijdelijk. Watchlist-alerts blijven gewoon werken.</p>
          <div className="flex gap-2">
            {[7, 14, 30].map(days => (
              <button
                key={days}
                onClick={() => pauseEmails(days)}
                disabled={pausing}
                className="flex-1 rounded-lg border border-border/30 px-3 py-2.5 text-sm font-medium text-text-muted transition-all hover:border-accent/30 hover:text-text disabled:opacity-50"
              >
                {days} dagen
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

// ── Toggle Row Component ─────────────────────────────────────────────────
function ToggleRow({ label, desc, checked, onChange }: {
  label: string;
  desc: string;
  checked: boolean;
  onChange: (val: boolean) => void;
}) {
  return (
    <label className="flex items-center justify-between gap-4 rounded-xl border border-border/20 bg-bg-elevated p-4 cursor-pointer">
      <div>
        <p className="font-medium text-text">{label}</p>
        <p className="text-xs text-text-muted">{desc}</p>
      </div>
      <button
        onClick={(e) => { e.preventDefault(); onChange(!checked); }}
        className={`h-6 w-10 shrink-0 rounded-full p-0.5 transition-colors ${checked ? 'bg-accent' : 'bg-border/50'}`}
      >
        <div className={`h-5 w-5 rounded-full bg-white transition-transform ${checked ? 'translate-x-4' : 'translate-x-0'}`}></div>
      </button>
    </label>
  );
}
