'use client';
import { Suspense, useActionState, useEffect, useRef, useState, useTransition } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { Icon } from '@/lib/icons';
import { AdImage } from '@/components/AdImage';
import { ListingCard } from '@/components/ListingCard';
import { AdCard } from '@/components/AdCard';
import { CITIES, type Ad, type Listing } from '@/lib/data';
import { useGo } from '@/lib/router';
import { useAuth } from '@/components/AuthProvider';
import { cancelReservation, deleteAd, setAdStatus, updateProfile, changePassword, deleteAccount, updateNotifPrefs, updateAvatar } from '@/lib/actions';
import { Messenger } from '@/components/Messenger';
import { NotificationsBell } from '@/components/NotificationsBell';
import { MobileSubnav } from '@/components/MobileSubnav';
import type { Thread } from '@/lib/queries';

export type Resa = {
  id: number;
  biz_id: number;
  bizName: string;
  bizCat: string;
  bizArea: string;
  bizPhotos: string[];
  day_num: number;
  month: string;
  time: string;
  covers: number;
  status: string;
  ref: string;
};
export type MyAd = {
  id: number;
  title: string;
  cat: string;
  price: string;
  city: string;
  cond: string;
  status: 'active' | 'paused' | 'sold';
  created_at: number;
  photos: string[];
};
export type CompteUser = { first: string; last: string; email: string; phone: string; city: string; avatar: string };

function whenLabel(ms: number): string {
  const diff = Date.now() - ms;
  const h = Math.floor(diff / 3_600_000);
  if (h < 1) return 'À l’instant';
  if (h < 24) return `il y a ${h}h`;
  return `il y a ${Math.floor(h / 24)}j`;
}

const STATUS = {
  active: { label: 'En ligne', bg: 'var(--teal-tint)', fg: 'var(--teal)' },
  paused: { label: 'En pause', bg: '#FBEFD9', fg: 'var(--amber)' },
  sold: { label: 'Vendu', bg: 'var(--bg2)', fg: 'var(--muted)' },
} as const;

const RESA_ST: Record<string, { bg: string; fg: string }> = {
  'Confirmée': { bg: 'var(--teal-tint)', fg: 'var(--teal)' },
  'En attente': { bg: '#FBEFD9', fg: 'var(--amber)' },
  'Honorée': { bg: 'var(--bg2)', fg: 'var(--sub)' },
  'Annulée': { bg: 'var(--red-tint)', fg: 'var(--red-dark)' },
};

function MesAnnonces({ myAds }: { myAds: MyAd[] }) {
  const { go } = useGo();
  const router = useRouter();
  const [filter, setFilter] = useState<'all' | 'active' | 'paused' | 'sold'>('all');
  const [, startTransition] = useTransition();
  const list = myAds.filter((a) => filter === 'all' || a.status === filter);
  const totals = {
    active: myAds.filter((a) => a.status === 'active').length,
    count: myAds.length,
  };
  const act = (fn: () => Promise<void>) => startTransition(async () => { await fn(); router.refresh(); });

  return (
    <div>
      <div className="grid cols-3" style={{ gap: 16, marginBottom: 22 }}>
        {(
          [
            ['Annonces en ligne', totals.active, 'tag'],
            ['Annonces publiées', totals.count, 'store'],
            ['Compte', '✓', 'user'],
          ] as const
        ).map((s, i) => (
          <div className="stat-card" key={i}>
            <div className="between"><Icon name={s[2]} size={20} stroke={1.8} style={{ color: 'var(--muted)' }} /></div>
            <div className="sv" style={{ marginTop: 12 }}>{s[1]}</div>
            <div className="small" style={{ marginTop: 2 }}>{s[0]}</div>
          </div>
        ))}
      </div>

      <div className="between" style={{ marginBottom: 16, flexWrap: 'wrap', gap: 12 }}>
        <div className="row gap8 wrapf">
          {(
            [
              ['all', 'Toutes'],
              ['active', 'En ligne'],
              ['paused', 'En pause'],
              ['sold', 'Vendues'],
            ] as const
          ).map(([k, l]) => (
            <div key={k} className={'chip ' + (filter === k ? 'active' : '')} onClick={() => setFilter(k)}>{l}</div>
          ))}
        </div>
        <button className="btn btn-red" onClick={() => go('post')}><Icon name="plus" size={17} stroke={2.5} />Déposer une annonce</button>
      </div>

      {list.length === 0 ? (
        <div className="panel empty">
          <div className="empty-ic"><Icon name="tag" size={30} stroke={1.6} /></div>
          <h3 className="h3" style={{ marginTop: 16 }}>Aucune annonce ici</h3>
          <p className="body" style={{ maxWidth: 340, margin: '6px auto 0' }}>Déposez votre première annonce, c’est gratuit et visible immédiatement.</p>
          <button className="btn btn-red" style={{ marginTop: 18 }} onClick={() => go('post')}>Déposer une annonce</button>
        </div>
      ) : (
        <div className="grid" style={{ gap: 12 }}>
          {list.map((a) => {
            const st = STATUS[a.status];
            return (
              <div className="myad" key={a.id}>
                <div className="myad-thumb" onClick={() => go('annonce', { id: a.id })} style={{ cursor: 'pointer' }}>
                  <AdImage photos={a.photos} cat={a.cat} h={96} radius={12} idx={a.id} />
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="row gap8" style={{ marginBottom: 4 }}>
                    <span className="badge-st" style={{ background: st.bg, color: st.fg }}>
                      <span style={{ width: 6, height: 6, borderRadius: 999, background: 'currentColor' }}></span>{st.label}
                    </span>
                    <span className="tiny">{whenLabel(a.created_at)}</span>
                  </div>
                  <div className="h4" style={{ fontSize: 16 }}>{a.title}</div>
                  <div className="h3" style={{ color: a.status === 'sold' ? 'var(--muted)' : 'var(--red)', fontSize: 18, marginTop: 2 }}>{a.price} DA</div>
                </div>
                <div className="myad-actions">
                  {a.status === 'active' && (
                    <button className="btn btn-soft btn-sm" onClick={() => act(() => setAdStatus(a.id, 'sold'))}>Marquer vendu</button>
                  )}
                  {a.status === 'paused' && (
                    <button className="btn btn-soft btn-sm" onClick={() => act(() => setAdStatus(a.id, 'active'))}>Réactiver</button>
                  )}
                  <button className="iconbtn" title="Modifier" onClick={() => go('post', { edit: a.id })}><Icon name="edit" size={17} /></button>
                  <button className="iconbtn danger" title="Supprimer" onClick={() => act(() => deleteAd(a.id))}><Icon name="x" size={18} /></button>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

function Favoris({ favBiz, favAds }: { favBiz: Listing[]; favAds: Ad[] }) {
  const { go } = useGo();
  const { isFav } = useAuth();
  const [sub, setSub] = useState<'annonces' | 'commerces'>('annonces');
  const ads = favAds.filter((a) => isFav('ad', a.id));
  const biz = favBiz.filter((b) => isFav('biz', b.id));
  const empty = sub === 'annonces' ? ads.length === 0 : biz.length === 0;
  return (
    <div>
      <div className="between" style={{ marginBottom: 20, flexWrap: 'wrap', gap: 12 }}>
        <div className="seg-tabs">
          <button className={sub === 'annonces' ? 'on' : ''} onClick={() => setSub('annonces')}>Annonces ({ads.length})</button>
          <button className={sub === 'commerces' ? 'on' : ''} onClick={() => setSub('commerces')}>Commerces ({biz.length})</button>
        </div>
      </div>
      {empty ? (
        <div className="panel empty">
          <div className="empty-ic"><Icon name="heart" size={30} stroke={1.6} /></div>
          <h3 className="h3" style={{ marginTop: 16 }}>Aucun favori pour l’instant</h3>
          <p className="body" style={{ maxWidth: 340, margin: '6px auto 0' }}>Touchez le cœur sur une annonce ou un commerce pour le retrouver ici.</p>
          <button className="btn btn-red" style={{ marginTop: 18 }} onClick={() => go(sub === 'annonces' ? 'annonces' : 'search')}>Parcourir</button>
        </div>
      ) : sub === 'annonces' ? (
        <div className="grid cols-3">{ads.map((d, i) => <AdCard key={d.id} d={d} idx={i} />)}</div>
      ) : (
        <div className="grid cols-3">{biz.map((d, i) => <ListingCard key={d.id} d={d} idx={i} />)}</div>
      )}
    </div>
  );
}

function MesReservations({ reservations }: { reservations: Resa[] }) {
  const { go } = useGo();
  const router = useRouter();
  const [, startCancel] = useTransition();
  const [when, setWhen] = useState<'upcoming' | 'past'>('upcoming');
  const cancel = (id: number) => startCancel(async () => { await cancelReservation(id); router.refresh(); });
  const upcoming = reservations;
  const past: Resa[] = [];
  const list = when === 'upcoming' ? upcoming : past;
  return (
    <div>
      <div className="seg-tabs" style={{ marginBottom: 20 }}>
        <button className={when === 'upcoming' ? 'on' : ''} onClick={() => setWhen('upcoming')}>À venir ({upcoming.length})</button>
        <button className={when === 'past' ? 'on' : ''} onClick={() => setWhen('past')}>Passées ({past.length})</button>
      </div>
      {list.length === 0 ? (
        <div className="panel empty">
          <div className="empty-ic"><Icon name="calendar" size={30} stroke={1.6} /></div>
          <h3 className="h3" style={{ marginTop: 16 }}>Aucune réservation {when === 'upcoming' ? 'à venir' : 'passée'}</h3>
          <p className="body" style={{ maxWidth: 340, margin: '6px auto 0' }}>Réservez une table, un soin ou une chambre en quelques secondes.</p>
          <button className="btn btn-red" style={{ marginTop: 18 }} onClick={() => go('search')}>Explorer les commerces</button>
        </div>
      ) : (
        <div className="grid" style={{ gap: 12 }}>
          {list.map((r) => {
            const st = RESA_ST[r.status] || RESA_ST['Confirmée'];
            return (
              <div className="resa" key={r.id}>
                <div className="resa-date"><span className="d">{r.day_num}</span><span className="m">{r.month}</span></div>
                <div className="conv-thumb" style={{ width: 62, height: 62, cursor: 'pointer' }} onClick={() => go('detail', { id: r.biz_id })}>
                  <AdImage biz photos={r.bizPhotos} cat={r.bizCat} h={62} radius={12} idx={r.id} />
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="row gap8" style={{ marginBottom: 4 }}>
                    <span className="badge-st" style={{ background: st.bg, color: st.fg }}>
                      <span style={{ width: 6, height: 6, borderRadius: 999, background: 'currentColor' }}></span>{r.status}
                    </span>
                    <span className="tiny tnum">{r.ref}</span>
                  </div>
                  <div className="h4" style={{ fontSize: 16 }}>{r.bizName}</div>
                  <div className="row gap16 small" style={{ marginTop: 6, flexWrap: 'wrap' }}>
                    <span className="row gap8"><Icon name="clock" size={14} stroke={1.8} />{r.time}</span>
                    <span className="row gap8"><Icon name="users" size={14} stroke={1.8} />{r.covers} pers.</span>
                    <span className="row gap8"><Icon name="pin" size={14} stroke={1.8} />{r.bizArea}</span>
                  </div>
                </div>
                <div className="myad-actions resa-actions">
                  <button className="btn btn-ghost btn-sm" onClick={() => go('detail', { id: r.biz_id })}>Modifier</button>
                  <button className="btn btn-soft btn-sm" onClick={() => cancel(r.id)}>Annuler</button>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

function Toggle({ on, onClick }: { on: boolean; onClick: () => void }) {
  return <div className={'switch ' + (on ? 'on' : '')} onClick={onClick}><div className="knob"></div></div>;
}

function PasswordPanel() {
  const [open, setOpen] = useState(false);
  const [state, action] = useActionState<{ ok?: boolean; error?: string }, FormData>(
    async (_prev, fd) => {
      const r = await changePassword(fd);
      return r;
    },
    {}
  );
  return (
    <div className="panel">
      <h3 className="h4" style={{ marginBottom: 6 }}>Sécurité</h3>
      <div className="setrow">
        <div className="setrow-ic"><Icon name="lock" size={18} stroke={1.8} /></div>
        <div style={{ flex: 1 }}>
          <div style={{ fontWeight: 600, fontSize: 14.5 }}>Mot de passe</div>
          <div className="small" style={{ marginTop: 2 }}>Choisissez un mot de passe fort et unique.</div>
        </div>
        <button className="btn btn-ghost btn-sm" onClick={() => setOpen((o) => !o)}>{open ? 'Fermer' : 'Modifier'}</button>
      </div>
      {open && (
        <form action={action} style={{ marginTop: 12 }}>
          <div className="field" style={{ marginBottom: 12 }}>
            <span className="label">Mot de passe actuel</span>
            <div className="input"><Icon name="lock" size={16} /><input name="current" type="password" placeholder="••••••••" /></div>
          </div>
          <div className="field">
            <span className="label">Nouveau mot de passe</span>
            <div className="input"><Icon name="lock" size={16} /><input name="new" type="password" placeholder="Au moins 6 caractères" /></div>
          </div>
          <div className="row gap12" style={{ marginTop: 14, alignItems: 'center' }}>
            <button className="btn btn-red btn-sm" type="submit"><Icon name="check" size={15} stroke={2.4} />Mettre à jour</button>
            {state.ok && <span className="small row gap8" style={{ color: 'var(--teal)', fontWeight: 600 }}><Icon name="checkCircle" size={15} />Mot de passe modifié</span>}
            {state.error && <span className="small" style={{ color: 'var(--red-dark)', fontWeight: 600 }}>{state.error}</span>}
          </div>
        </form>
      )}
    </div>
  );
}

function DeletePanel() {
  const [open, setOpen] = useState(false);
  const [state, action] = useActionState<{ ok?: boolean; error?: string }, FormData>(
    async (_prev, fd) => deleteAccount(fd),
    {}
  );
  return (
    <div className="panel" style={{ borderColor: 'var(--red-tint)' }}>
      <div className="between" style={{ flexWrap: 'wrap', gap: 12 }}>
        <div>
          <div style={{ fontWeight: 700, fontSize: 14.5, color: 'var(--red-dark)' }}>Supprimer mon compte</div>
          <div className="small" style={{ marginTop: 2 }}>Cette action est définitive et irréversible.</div>
        </div>
        <button className="btn btn-soft btn-sm" onClick={() => setOpen((o) => !o)}><Icon name="x" size={16} />{open ? 'Annuler' : 'Supprimer le compte'}</button>
      </div>
      {open && (
        <form action={action} style={{ marginTop: 14 }}>
          <div className="field">
            <span className="label">Confirmez avec votre mot de passe</span>
            <div className="input"><Icon name="lock" size={16} /><input name="password" type="password" placeholder="••••••••" /></div>
          </div>
          {state.error && <div className="small" style={{ color: 'var(--red-dark)', fontWeight: 600, marginTop: 8 }}>{state.error}</div>}
          <button className="btn btn-red btn-sm" type="submit" style={{ marginTop: 12 }}><Icon name="x" size={15} stroke={2.4} />Supprimer définitivement</button>
        </form>
      )}
    </div>
  );
}

const NOTIF_DEFAULTS: Record<string, boolean> = { msg: true, resa: true, promo: false, news: false };

function Parametres({ user, notifPrefs }: { user: CompteUser; notifPrefs: Record<string, boolean> }) {
  const router = useRouter();
  const { logout } = useAuth();
  const [notif, setNotif] = useState<Record<string, boolean>>({ ...NOTIF_DEFAULTS, ...notifPrefs });
  const [lang, setLang] = useState<'fr' | 'ar'>('fr');
  const [, startSave] = useTransition();
  const avatarRef = useRef<HTMLInputElement>(null);
  const flip = (k: string) => {
    const next = { ...notif, [k]: !notif[k] };
    setNotif(next);
    startSave(() => { updateNotifPrefs(next); });
  };
  const onAvatar = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    const fd = new FormData();
    fd.set('avatar', file);
    startSave(async () => { await updateAvatar(fd); router.refresh(); });
    e.target.value = '';
  };
  const [profileState, saveProfile] = useActionState<{ ok?: boolean; error?: string }, FormData>(
    async (_prev, fd) => updateProfile(fd),
    {}
  );
  return (
    <div className="grid" style={{ gridTemplateColumns: '1fr', gap: 16, maxWidth: 760 }}>
      <form className="panel" action={saveProfile}>
        <h3 className="h4" style={{ marginBottom: 18 }}>Profil</h3>
        <div className="row gap16" style={{ marginBottom: 20 }}>
          {user.avatar ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img src={user.avatar} alt="" style={{ width: 64, height: 64, borderRadius: 999, objectFit: 'cover' }} />
          ) : (
            <div className="avatar" style={{ background: 'var(--red)', width: 64, height: 64, fontSize: 24 }}>
              {(user.first || user.email || 'A').charAt(0).toUpperCase()}
            </div>
          )}
          <div>
            <input ref={avatarRef} type="file" accept="image/*" onChange={onAvatar} style={{ display: 'none' }} />
            <button type="button" className="btn btn-ghost btn-sm" onClick={() => avatarRef.current?.click()}><Icon name="camera" size={15} />Changer la photo</button>
            <div className="tiny" style={{ marginTop: 6 }}>JPG, PNG ou WebP, 6 Mo max.</div>
          </div>
        </div>
        <div className="grid cols-2" style={{ gap: 14 }}>
          <div className="field"><span className="label">Prénom</span><div className="input"><input name="first" defaultValue={user.first} /></div></div>
          <div className="field"><span className="label">Nom</span><div className="input"><input name="last" defaultValue={user.last} /></div></div>
        </div>
        <div className="field" style={{ marginTop: 14 }}>
          <span className="label">E-mail</span>
          <div className="input"><Icon name="mail" size={16} /><input name="email" type="email" defaultValue={user.email} /></div>
        </div>
        <div className="grid cols-2" style={{ gap: 14, marginTop: 14 }}>
          <div className="field"><span className="label">Téléphone</span><div className="input"><Icon name="phone" size={16} /><input name="phone" defaultValue={user.phone} placeholder="+213 6 .. .. .. .." /></div></div>
          <div className="field"><span className="label">Ville</span>
            <div className="input"><Icon name="pin" size={16} /><select name="city" defaultValue={user.city || 'Alger'} style={{ border: 'none', outline: 'none', background: 'none', width: '100%' }}>{CITIES.map((c) => <option key={c}>{c}</option>)}</select></div>
          </div>
        </div>
        <div className="row gap12" style={{ marginTop: 18, alignItems: 'center' }}>
          <button className="btn btn-red" type="submit"><Icon name="check" size={16} stroke={2.5} />Enregistrer</button>
          {profileState.ok && <span className="small row gap8" style={{ color: 'var(--teal)', fontWeight: 600 }}><Icon name="checkCircle" size={16} />Profil enregistré</span>}
          {profileState.error && <span className="small" style={{ color: 'var(--red-dark)', fontWeight: 600 }}>{profileState.error}</span>}
        </div>
      </form>

      <div className="panel">
        <h3 className="h4" style={{ marginBottom: 6 }}>Notifications</h3>
        {(
          [
            ['msg', 'message', 'Messages', 'Quand un acheteur ou vendeur vous écrit'],
            ['resa', 'calendar', 'Réservations', 'Confirmations et rappels de vos réservations'],
            ['promo', 'tag', 'Promotions', 'Bons plans et offres des commerces près de chez vous'],
            ['news', 'bell', 'Actualités Darsouk', 'Nouveautés de la plateforme'],
          ] as const
        ).map(([k, ic, t, d]) => (
          <div className="setrow" key={k}>
            <div className="setrow-ic"><Icon name={ic} size={18} stroke={1.8} /></div>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 600, fontSize: 14.5 }}>{t}</div>
              <div className="small" style={{ marginTop: 2 }}>{d}</div>
            </div>
            <Toggle on={notif[k as keyof typeof notif]} onClick={() => flip(k as keyof typeof notif)} />
          </div>
        ))}
      </div>

      <div className="panel">
        <h3 className="h4" style={{ marginBottom: 16 }}>Préférences</h3>
        <div className="between">
          <div><div style={{ fontWeight: 600, fontSize: 14.5 }}>Langue</div><div className="small" style={{ marginTop: 2 }}>Langue de l’interface</div></div>
          <div className="seg-tabs">
            <button className={lang === 'fr' ? 'on' : ''} onClick={() => setLang('fr')}>Français</button>
            <button className={lang === 'ar' ? 'on' : ''} onClick={() => setLang('ar')}>العربية</button>
          </div>
        </div>
      </div>

      <PasswordPanel />

      <DeletePanel />

      <button className="row gap8" style={{ fontWeight: 600, fontSize: 14, color: 'var(--sub)', justifyContent: 'center', padding: 8 }} onClick={logout}>
        <Icon name="logout" size={17} stroke={1.9} />Se déconnecter
      </button>
    </div>
  );
}

type CompteTab = 'annonces' | 'messages' | 'favoris' | 'resas' | 'params';

function CompteScreen({ user, reservations, myAds, favBiz, favAds, threads, unread, notifPrefs }: CompteClientProps) {
  const { go } = useGo();
  const { logout } = useAuth();
  const sp = useSearchParams();
  const urlTab = (sp?.get('tab') as CompteTab) || null;
  const [tab, setTab] = useState<CompteTab>(urlTab || 'annonces');
  // Only re-sync when the URL's tab actually changes (e.g. from the bottom tab bar),
  // not on every router.refresh — otherwise a refresh would reset the active tab.
  useEffect(() => {
    if (urlTab) setTab(urlTab);
  }, [urlTab]);
  const convParam = sp?.get('conv');
  const initialConvId = convParam ? Number(convParam) : undefined;

  const NAV: [CompteTab, string, string, number][] = [
    ['annonces', 'tag', 'Mes annonces', 0],
    ['messages', 'message', 'Messagerie', unread],
    ['favoris', 'heart', 'Favoris', 0],
    ['resas', 'calendar', 'Mes réservations', 0],
    ['params', 'settings', 'Paramètres', 0],
  ];
  const titles: Record<CompteTab, string> = {
    annonces: 'Mes annonces', messages: 'Messagerie', favoris: 'Favoris', resas: 'Mes réservations', params: 'Paramètres',
  };
  const subs: Record<CompteTab, string> = {
    annonces: 'Gérez vos annonces et suivez leurs performances.',
    messages: 'Échangez avec les acheteurs et les vendeurs.',
    favoris: 'Vos annonces et commerces sauvegardés.',
    resas: 'Suivez vos réservations à venir et passées.',
    params: 'Gérez votre profil, vos notifications et votre sécurité.',
  };

  return (
    <div className="pro-shell">
      <div className="pro-side">
        <div className="row gap8" style={{ padding: '6px 10px 16px' }}>
          <img src="/assets/darsouk-logo.png" alt="Darsouk" style={{ height: 22, cursor: 'pointer' }} onClick={() => go('home')} />
        </div>
        <div className="pl" style={{ pointerEvents: 'none', opacity: 1 }}>
          {user.avatar ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img src={user.avatar} alt="" style={{ width: 30, height: 30, borderRadius: 999, objectFit: 'cover' }} />
          ) : (
            <div className="avatar" style={{ background: 'var(--red)', width: 30, height: 30, fontSize: 13 }}>
              {(user.first || user.email || 'A').charAt(0).toUpperCase()}
            </div>
          )}
          <span className="hide-side" style={{ color: '#fff' }}>{user.first ? `${user.first} ${user.last}`.trim() : user.email}</span>
        </div>
        <div style={{ height: 1, background: 'rgba(255,255,255,0.12)', margin: '8px 4px' }}></div>
        {NAV.map(([k, ic, lb, badge]) => (
          <div key={k} className={'pl ' + (tab === k ? 'on' : '')} onClick={() => setTab(k)}>
            <Icon name={ic} size={19} stroke={1.8} /><span className="hide-side">{lb}</span>
            {badge > 0 && <span className="conv-unread hide-side" style={{ marginLeft: 'auto' }}>{badge}</span>}
          </div>
        ))}
        <div style={{ marginTop: 'auto' }} className="hide-side">
          <div className="pl" onClick={logout}><Icon name="logout" size={19} stroke={1.8} />Déconnexion</div>
        </div>
      </div>

      <div className="pro-main">
        <MobileSubnav items={NAV.map(([k, ic, lb, badge]) => [k, ic, lb, badge])} active={tab} onSelect={(k) => setTab(k as CompteTab)} />
        <div className="between" style={{ marginBottom: 22, flexWrap: 'wrap', gap: 12 }}>
          <div>
            <h1 className="h2">{titles[tab]}</h1>
            {subs[tab] && <p className="small" style={{ marginTop: 4 }}>{subs[tab]}</p>}
          </div>
          <div className="row gap12">
            <NotificationsBell />
            <button className="btn btn-ghost btn-sm" onClick={() => go('annonces')}><Icon name="store" size={16} />Parcourir</button>
          </div>
        </div>

        {tab === 'annonces' && <MesAnnonces myAds={myAds} />}
        {tab === 'messages' && <Messenger threads={threads} initialConvId={initialConvId} />}
        {tab === 'favoris' && <Favoris favBiz={favBiz} favAds={favAds} />}
        {tab === 'resas' && <MesReservations reservations={reservations} />}
        {tab === 'params' && <Parametres user={user} notifPrefs={notifPrefs} />}
      </div>
    </div>
  );
}

export type CompteClientProps = {
  user: CompteUser;
  reservations: Resa[];
  myAds: MyAd[];
  favBiz: Listing[];
  favAds: Ad[];
  threads: Thread[];
  unread: number;
  notifPrefs: Record<string, boolean>;
};

export function CompteClient(props: CompteClientProps) {
  return (
    <Suspense fallback={null}>
      <CompteScreen {...props} />
    </Suspense>
  );
}
