'use client';
import { useState, useTransition } from 'react';
import { useRouter } from 'next/navigation';
import { Icon, Stars } from '@/lib/icons';
import { AdImage } from '@/components/AdImage';
import { useGo } from '@/lib/router';
import { useAuth } from '@/components/AuthProvider';
import { Messenger } from '@/components/Messenger';
import { BusinessEditor } from '@/components/BusinessEditor';
import { NotificationsBell } from '@/components/NotificationsBell';
import { MobileSubnav } from '@/components/MobileSubnav';
import { setReservationStatus, replyToReview } from '@/lib/actions';
import type { Thread, OwnerBusiness, ProReservation, Review, ReviewStats } from '@/lib/queries';

const NAV: [ProTab, string, string][] = [
  ['dash', 'chart', 'Tableau de bord'],
  ['resas', 'calendar', 'Réservations'],
  ['messages', 'message', 'Messagerie'],
  ['fiche', 'store', 'Ma fiche'],
  ['avis', 'star', 'Avis'],
  ['stats', 'trending', 'Statistiques'],
  ['abo', 'card', 'Abonnement'],
  ['set', 'settings', 'Paramètres'],
];
type ProTab = 'dash' | 'resas' | 'messages' | 'fiche' | 'avis' | 'stats' | 'abo' | 'set';

function LineChart({ data, color = 'var(--red)', h = 180 }: { data: number[]; color?: string; h?: number }) {
  const max = Math.max(...data) * 1.15;
  const w = 600;
  const pts = data.map((v, i): [number, number] => [(i / (data.length - 1)) * w, h - (v / max) * h]);
  const path = pts.map((p, i) => (i === 0 ? 'M' : 'L') + p[0].toFixed(1) + ' ' + p[1].toFixed(1)).join(' ');
  const area = path + ` L${w} ${h} L0 ${h} Z`;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" style={{ width: '100%', height: h, display: 'block', overflow: 'visible' }}>
      <defs>
        <linearGradient id="lg" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity="0.18" />
          <stop offset="100%" stopColor={color} stopOpacity="0" />
        </linearGradient>
      </defs>
      {[0.25, 0.5, 0.75].map((g) => (
        <line key={g} x1="0" y1={h * g} x2={w} y2={h * g} stroke="var(--line2)" strokeWidth="1" />
      ))}
      <path d={area} fill="url(#lg)" />
      <path d={path} fill="none" stroke={color} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
      {pts.map((p, i) => <circle key={i} cx={p[0]} cy={p[1]} r={i === pts.length - 1 ? 4.5 : 0} fill={color} />)}
    </svg>
  );
}

function Donut({ segments, size = 150 }: { segments: { l: string; v: number; c: string }[]; size?: number }) {
  const total = segments.reduce((s, x) => s + x.v, 0);
  const r = 54;
  const C = 2 * Math.PI * r;
  let off = 0;
  return (
    <svg viewBox="0 0 150 150" style={{ width: size, height: size }}>
      <circle cx="75" cy="75" r={r} fill="none" stroke="var(--bg2)" strokeWidth="18" />
      {segments.map((s, i) => {
        const len = (s.v / total) * C;
        const el = (
          <circle
            key={i}
            cx="75"
            cy="75"
            r={r}
            fill="none"
            stroke={s.c}
            strokeWidth="18"
            strokeDasharray={`${len} ${C - len}`}
            strokeDashoffset={-off}
            transform="rotate(-90 75 75)"
            strokeLinecap="butt"
          />
        );
        off += len;
        return el;
      })}
      <text x="75" y="71" textAnchor="middle" fontFamily="var(--disp)" fontWeight={800} fontSize="26" fill="var(--ink)">{total}</text>
      <text x="75" y="90" textAnchor="middle" fontFamily="var(--body)" fontSize="11" fill="var(--muted)">vues / jour</text>
    </svg>
  );
}

function Stats() {
  const [range, setRange] = useState('30');
  const views = [120, 145, 138, 172, 165, 198, 210, 188, 225, 240, 232, 268, 255, 290];
  const resa = [8, 11, 9, 14, 12, 18, 22, 19, 24, 21, 26, 28, 25, 31];
  const sources = [
    { l: 'Recherche Darsouk', v: 142, c: 'var(--red)' },
    { l: 'Catégories', v: 78, c: 'var(--teal)' },
    { l: 'Favoris & partage', v: 44, c: 'var(--gold)' },
    { l: 'Direct', v: 26, c: '#6C5CE7' },
  ];
  const top: [string, number][] = [
    ['Tajine d’agneau', 86],
    ['Couscous royal', 72],
    ['Pastilla au poulet', 54],
    ['Thé à la menthe', 48],
  ];
  return (
    <div>
      <div className="between" style={{ marginBottom: 18, flexWrap: 'wrap', gap: 12 }}>
        <div className="seg-tabs">
          {(
            [
              ['7', '7 jours'],
              ['30', '30 jours'],
              ['90', '3 mois'],
            ] as const
          ).map(([k, l]) => (
            <button key={k} className={range === k ? 'on' : ''} onClick={() => setRange(k)}>{l}</button>
          ))}
        </div>
        <button className="btn btn-ghost btn-sm"><Icon name="arrowUpRight" size={15} />Exporter</button>
      </div>

      <div className="grid cols-4" style={{ gap: 16, marginBottom: 16 }}>
        {(
          [
            ['Vues de la fiche', '6 842', '+18%', 'eye'],
            ['Réservations', '312', '+12%', 'calendar'],
            ['Taux de conversion', '4.6%', '+0.4%', 'trending'],
            ['Panier moyen', '2 150 DA', '+6%', 'banknote'],
          ] as const
        ).map((s, i) => (
          <div className="stat-card" key={i}>
            <div className="between">
              <Icon name={s[3]} size={20} stroke={1.8} style={{ color: 'var(--muted)' }} />
              <span className="delta up"><Icon name="trending" size={12} stroke={2.5} />{s[2]}</span>
            </div>
            <div className="sv" style={{ marginTop: 14 }}>{s[1]}</div>
            <div className="small" style={{ marginTop: 2 }}>{s[0]}</div>
          </div>
        ))}
      </div>

      <div className="grid" style={{ gridTemplateColumns: '1.5fr 1fr', gap: 16, marginBottom: 16 }}>
        <div className="panel">
          <div className="between" style={{ marginBottom: 18 }}>
            <h3 className="h4">Vues de la fiche</h3>
            <span className="small row gap8">
              <span style={{ width: 9, height: 9, borderRadius: 999, background: 'var(--red)' }}></span>Vues quotidiennes
            </span>
          </div>
          <LineChart data={views} />
        </div>
        <div className="panel">
          <h3 className="h4" style={{ marginBottom: 14 }}>Provenance du trafic</h3>
          <div className="row gap16" style={{ alignItems: 'center' }}>
            <Donut segments={sources} />
            <div style={{ flex: 1 }}>
              {sources.map((s) => (
                <div key={s.l} className="between" style={{ padding: '5px 0' }}>
                  <span className="row gap8 small">
                    <span style={{ width: 9, height: 9, borderRadius: 3, background: s.c }}></span>{s.l}
                  </span>
                  <span className="small tnum" style={{ fontWeight: 700 }}>{s.v}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: '1.5fr 1fr', gap: 16 }}>
        <div className="panel">
          <div className="between" style={{ marginBottom: 18 }}>
            <h3 className="h4">Réservations</h3>
            <span className="small row gap8">
              <span style={{ width: 9, height: 9, borderRadius: 999, background: 'var(--teal)' }}></span>Par jour
            </span>
          </div>
          <LineChart data={resa} color="var(--teal)" />
        </div>
        <div className="panel">
          <h3 className="h4" style={{ marginBottom: 14 }}>Plats les plus consultés</h3>
          <div className="grid" style={{ gap: 12 }}>
            {top.map(([n, v]) => (
              <div key={n}>
                <div className="between" style={{ marginBottom: 5 }}>
                  <span className="small" style={{ fontWeight: 600, color: 'var(--ink)' }}>{n}</span>
                  <span className="tiny tnum">{v}</span>
                </div>
                <div style={{ height: 7, borderRadius: 999, background: 'var(--bg2)', overflow: 'hidden' }}>
                  <div
                    style={{
                      width: (v / top[0][1]) * 100 + '%',
                      height: '100%',
                      background: 'linear-gradient(90deg,var(--red),#FF7A6B)',
                      borderRadius: 999,
                    }}
                  ></div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}


function Avis({ reviews, stats, bizName }: { reviews: Review[]; stats: ReviewStats; bizName: string }) {
  const router = useRouter();
  const [filter, setFilter] = useState(0);
  const [replyTo, setReplyTo] = useState<number | null>(null);
  const [draft, setDraft] = useState('');
  const [, startReply] = useTransition();
  const total = stats.count;
  const list = filter ? reviews.filter((r) => r.rating === filter) : reviews;
  const pendingReply = reviews.filter((r) => !r.reply).length;

  const submitReply = (id: number) => {
    const text = draft.trim() || 'Merci pour votre retour !';
    setReplyTo(null);
    setDraft('');
    startReply(async () => { await replyToReview(id, text); router.refresh(); });
  };

  if (total === 0) {
    return (
      <div className="panel empty">
        <div className="empty-ic"><Icon name="star" size={30} stroke={1.6} /></div>
        <h3 className="h3" style={{ marginTop: 16 }}>Aucun avis pour l’instant</h3>
        <p className="body" style={{ maxWidth: 360, margin: '6px auto 0' }}>Les avis laissés par vos clients après leur réservation apparaîtront ici.</p>
      </div>
    );
  }

  return (
    <div>
      <div className="grid" style={{ gridTemplateColumns: '300px 1fr', gap: 16, marginBottom: 8 }}>
        <div className="panel" style={{ textAlign: 'center' }}>
          <div className="h1" style={{ fontSize: 52 }}>{stats.avg.toFixed(1)}</div>
          <Stars value={Math.round(stats.avg)} size={18} />
          <div className="small" style={{ marginTop: 8 }}>{total} avis</div>
        </div>
        <div className="panel">
          {stats.dist.map(([star, n]) => (
            <div key={star} className="row gap12" style={{ padding: '5px 0', cursor: 'pointer' }} onClick={() => setFilter(filter === star ? 0 : star)}>
              <span className="row gap8" style={{ width: 42, fontWeight: 600, fontSize: 13 }}>
                {star}<Icon name="star" size={13} fill="var(--gold)" style={{ color: 'var(--gold)' }} />
              </span>
              <div style={{ flex: 1, height: 8, borderRadius: 999, background: 'var(--bg2)', overflow: 'hidden' }}>
                <div style={{ width: (total ? (n / total) * 100 : 0) + '%', height: '100%', background: filter === star ? 'var(--red)' : 'var(--gold)', borderRadius: 999 }}></div>
              </div>
              <span className="tnum small" style={{ width: 36, textAlign: 'right' }}>{n}</span>
            </div>
          ))}
        </div>
      </div>

      <div className="between" style={{ margin: '20px 0 14px', flexWrap: 'wrap', gap: 12 }}>
        <div className="row gap8 wrapf">
          <div className={'chip ' + (filter === 0 ? 'active' : '')} onClick={() => setFilter(0)}>Tous</div>
          {[5, 4, 3].map((s) => (
            <div key={s} className={'chip ' + (filter === s ? 'active' : '')} onClick={() => setFilter(s)}>{s} étoiles</div>
          ))}
        </div>
        {pendingReply > 0 && <div className="small"><b style={{ color: 'var(--teal)' }}>{pendingReply} avis</b> en attente de réponse</div>}
      </div>

      <div className="grid" style={{ gap: 12 }}>
        {list.map((rv) => (
          <div className="panel" key={rv.id}>
            <div className="between">
              <div className="row gap12">
                <div className="avatar" style={{ background: rv.color }}>{rv.author[0]?.toUpperCase()}</div>
                <div>
                  <div style={{ fontWeight: 700, fontSize: 14 }}>{rv.author}</div>
                  <div className="tiny">{rv.when}</div>
                </div>
              </div>
              <Stars value={rv.rating} size={14} />
            </div>
            {rv.body && <p className="body" style={{ marginTop: 12 }}>{rv.body}</p>}
            {rv.reply ? (
              <div style={{ marginTop: 12, marginLeft: 16, padding: '12px 16px', background: 'var(--bg2)', borderRadius: 12, borderLeft: '3px solid var(--red)' }}>
                <div className="row gap8" style={{ marginBottom: 4 }}>
                  <Icon name="store" size={14} stroke={1.8} style={{ color: 'var(--red)' }} />
                  <span style={{ fontWeight: 700, fontSize: 13 }}>Réponse de {bizName}</span>
                </div>
                <p className="small" style={{ color: 'var(--sub)' }}>{rv.reply}</p>
              </div>
            ) : replyTo === rv.id ? (
              <div style={{ marginTop: 12 }}>
                <div className="input" style={{ alignItems: 'flex-start' }}>
                  <textarea autoFocus value={draft} onChange={(e) => setDraft(e.target.value)} rows={2} placeholder="Rédigez une réponse publique…" style={{ border: 'none', outline: 'none', background: 'none', width: '100%', resize: 'vertical', fontSize: 14 }} />
                </div>
                <div className="row gap8" style={{ marginTop: 10, justifyContent: 'flex-end' }}>
                  <button className="btn btn-ghost btn-sm" onClick={() => { setReplyTo(null); setDraft(''); }}>Annuler</button>
                  <button className="btn btn-red btn-sm" onClick={() => submitReply(rv.id)}>Publier la réponse</button>
                </div>
              </div>
            ) : (
              <button className="btn btn-ghost btn-sm" style={{ marginTop: 12 }} onClick={() => setReplyTo(rv.id)}>
                <Icon name="message" size={15} />Répondre
              </button>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}

const RESAS = [
  { c: 'Yacine Belkacem', cov: 4, d: 'Auj. · 20:30', st: 'Confirmée', stc: 'open', ref: 'DSK-4821' },
  { c: 'Lila Mansouri', cov: 2, d: 'Auj. · 21:00', st: 'Confirmée', stc: 'open', ref: 'DSK-4822' },
  { c: 'Karim Daoudi', cov: 6, d: 'Dem. · 13:00', st: 'En attente', stc: 'soon', ref: 'DSK-4823' },
  { c: 'Nadia Cherif', cov: 3, d: 'Dem. · 20:00', st: 'Confirmée', stc: 'open', ref: 'DSK-4824' },
  { c: 'Sofiane Atallah', cov: 2, d: 'Jeu · 19:30', st: 'En attente', stc: 'soon', ref: 'DSK-4825' },
] as const;

function Bars() {
  const data = [40, 62, 55, 78, 95, 120, 88];
  const days = ['Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam', 'Dim'];
  const max = 120;
  return (
    <div>
      <div className="bars">
        {data.map((v, i) => (
          <div
            key={i}
            className="bar"
            style={{
              height: (v / max) * 100 + '%',
              background: i === 5
                ? 'linear-gradient(180deg,var(--red),#FF7A6B)'
                : 'linear-gradient(180deg,#E7B7AE,#F2D3CC)',
            }}
            title={v + ' réservations'}
          />
        ))}
      </div>
      <div className="row" style={{ justifyContent: 'space-between', marginTop: 8 }}>
        {days.map((d) => <span key={d} className="tiny" style={{ flex: 1, textAlign: 'center' }}>{d}</span>)}
      </div>
    </div>
  );
}

function StatusBadge({ st, stc }: { st: string; stc: string }) {
  return (
    <span
      className="badge-st"
      style={stc === 'open'
        ? { background: 'var(--teal-tint)', color: 'var(--teal)' }
        : { background: '#FBEFD9', color: 'var(--amber)' }}
    >
      <span style={{ width: 6, height: 6, borderRadius: 999, background: 'currentColor' }}></span>{st}
    </span>
  );
}

export function ProClient({
  business,
  reservations = [],
  reviews = [],
  reviewStats = { avg: 0, count: 0, dist: [] },
  threads = [],
  proUnread = 0,
  bizName: bizNameProp,
}: {
  business?: OwnerBusiness | null;
  reservations?: ProReservation[];
  reviews?: Review[];
  reviewStats?: ReviewStats;
  threads?: Thread[];
  proUnread?: number;
  bizName?: string;
}) {
  const { go } = useGo();
  const { logout } = useAuth();
  const router = useRouter();
  const [, startResa] = useTransition();
  const [tab, setTab] = useState<ProTab>('dash');
  const bizName = bizNameProp || 'votre commerce';
  const greeting = bizNameProp ? `Bonjour, ${bizNameProp} 👋` : 'Bonjour 👋';
  const proUnreadTotal = proUnread;
  const pendingResas = reservations.filter((r) => r.status === 'En attente');
  const resaAction = (id: number, status: 'Confirmée' | 'Refusée') =>
    startResa(async () => { await setReservationStatus(id, status); router.refresh(); });

  const Header = ({ title, sub }: { title: string; sub?: string }) => (
    <div className="between" style={{ marginBottom: 22, flexWrap: 'wrap', gap: 12 }}>
      <div>
        <h1 className="h2">{title}</h1>
        {sub && <p className="small" style={{ marginTop: 4 }}>{sub}</p>}
      </div>
      <div className="row gap12">
        <button className="btn btn-ghost btn-sm" onClick={() => business && go('detail', { id: business.id })}>
          <Icon name="eye" size={16} />Voir ma fiche
        </button>
        <NotificationsBell />
        <div className="avatar" style={{ background: 'var(--red)', width: 38, height: 38 }}>{bizName.charAt(0).toUpperCase()}</div>
      </div>
    </div>
  );

  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')}
          />
          <span
            style={{
              background: 'var(--red)',
              color: '#fff',
              fontWeight: 800,
              fontSize: 10,
              padding: '3px 7px',
              borderRadius: 6,
            }}
            className="hide-side"
          >
            PRO
          </span>
        </div>
        {NAV.map(([k, ic, lb]) => {
          const proUnread = k === 'messages' ? proUnreadTotal : 0;
          return (
            <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>
              {proUnread > 0 && (
                <span className="conv-unread hide-side" style={{ marginLeft: 'auto' }}>{proUnread}</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]) => [k, ic, lb, k === 'messages' ? proUnreadTotal : 0])}
          active={tab}
          onSelect={(k) => setTab(k as ProTab)}
        />
        {tab === 'dash' && (
          <div>
            <Header title={greeting} sub="Voici l’activité de votre établissement cette semaine." />
            <div className="grid cols-4" style={{ gap: 16 }}>
              {(
                [
                  ['Vues de la fiche', '3 248', '+12%', 'eye'],
                  ['Réservations', '142', '+8%', 'calendar'],
                  ['Taux de remplissage', '78%', '+5%', 'users'],
                  ['Note moyenne', '4.9', '+0.1', 'star'],
                ] as const
              ).map((s, i) => (
                <div className="stat-card" key={i}>
                  <div className="between">
                    <Icon name={s[3]} size={20} stroke={1.8} style={{ color: 'var(--muted)' }} />
                    <span className="delta up"><Icon name="trending" size={12} stroke={2.5} />{s[2]}</span>
                  </div>
                  <div className="sv" style={{ marginTop: 14 }}>{s[1]}</div>
                  <div className="small" style={{ marginTop: 2 }}>{s[0]}</div>
                </div>
              ))}
            </div>
            <div className="grid" style={{ gridTemplateColumns: '1.5fr 1fr', gap: 16, marginTop: 16 }}>
              <div className="panel">
                <div className="between" style={{ marginBottom: 16 }}>
                  <h3 className="h4">Réservations cette semaine</h3>
                  <span className="seg"><button className="on">7 jours</button><button>30 jours</button></span>
                </div>
                <Bars />
              </div>
              <div className="panel">
                <h3 className="h4" style={{ marginBottom: 14 }}>Votre fiche</h3>
                <AdImage biz photos={business?.photos} cat={business?.cat || 'restaurants'} h={120} radius={12} />
                <div className="h4" style={{ marginTop: 12 }}>{bizName}</div>
                <div className="row gap8" style={{ marginTop: 6 }}>
                  <Stars value={Math.round(reviewStats.avg) || 0} size={13} />
                  <span className="small">{reviewStats.count ? `${reviewStats.avg.toFixed(1)} · ${reviewStats.count} avis` : 'Aucun avis'}</span>
                </div>
                <div className="row gap8" style={{ marginTop: 12 }}>
                  <span className="chip chip-sm" style={{ background: 'var(--teal-tint)', color: 'var(--teal)', border: 'none' }}>
                    <Icon name="verified" size={13} />Vérifié
                  </span>
                  <span className="chip chip-sm" style={{ background: 'var(--red-tint)', color: 'var(--red-dark)', border: 'none' }}>Pro</span>
                </div>
                <button className="btn btn-ghost btn-block btn-sm" style={{ marginTop: 14 }} onClick={() => setTab('fiche')}>
                  <Icon name="edit" size={15} />Modifier ma fiche
                </button>
              </div>
            </div>
            <div className="panel" style={{ marginTop: 16 }}>
              <div className="between" style={{ marginBottom: 8 }}>
                <h3 className="h4">Réservations à venir</h3>
                <a
                  className="small"
                  style={{ fontWeight: 600, color: 'var(--red-dark)', cursor: 'pointer' }}
                  onClick={() => setTab('resas')}
                >
                  Tout voir
                </a>
              </div>
              <table className="tbl">
                <thead>
                  <tr>
                    <th>Client</th><th>Couverts</th><th>Quand</th><th>Statut</th><th className="hide-m">Réf.</th>
                  </tr>
                </thead>
                <tbody>
                  {RESAS.slice(0, 4).map((r, i) => (
                    <tr key={i}>
                      <td style={{ fontWeight: 600 }}>{r.c}</td>
                      <td>{r.cov}</td>
                      <td>{r.d}</td>
                      <td><StatusBadge st={r.st} stc={r.stc} /></td>
                      <td className="hide-m tnum small">{r.ref}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {tab === 'resas' && (
          <div>
            <Header title="Réservations" sub="Gérez les demandes de réservation de vos clients." />
            {!business ? (
              <div className="panel empty">
                <div className="empty-ic"><Icon name="calendar" size={30} stroke={1.6} /></div>
                <h3 className="h3" style={{ marginTop: 16 }}>Créez d’abord votre fiche</h3>
                <p className="body" style={{ maxWidth: 360, margin: '6px auto 0' }}>Une fois votre commerce publié, les réservations de vos clients apparaîtront ici.</p>
                <button className="btn btn-red" style={{ marginTop: 18 }} onClick={() => setTab('fiche')}>Créer ma fiche</button>
              </div>
            ) : reservations.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 pour l’instant</h3>
                <p className="body" style={{ maxWidth: 360, margin: '6px auto 0' }}>Les demandes de vos clients s’afficheront ici, à accepter ou refuser.</p>
              </div>
            ) : (
              <div className="panel">
                <table className="tbl">
                  <thead>
                    <tr>
                      <th>Client</th><th>Couverts</th><th>Quand</th><th>Statut</th>
                      <th className="hide-m">Réf.</th><th></th>
                    </tr>
                  </thead>
                  <tbody>
                    {reservations.map((r) => {
                      const stc = r.status === 'Confirmée' ? 'open' : r.status === 'Refusée' ? 'closed' : 'soon';
                      return (
                        <tr key={r.id}>
                          <td style={{ fontWeight: 600 }}>{r.customer}</td>
                          <td>{r.covers}</td>
                          <td>{r.day_num} {r.month} · {r.time}</td>
                          <td><StatusBadge st={r.status} stc={stc} /></td>
                          <td className="hide-m tnum small">{r.ref}</td>
                          <td style={{ textAlign: 'right' }}>
                            {r.status === 'En attente' ? (
                              <span className="row gap8" style={{ justifyContent: 'flex-end' }}>
                                <button className="btn btn-soft btn-sm" onClick={() => resaAction(r.id, 'Confirmée')}>Accepter</button>
                                <button className="btn btn-ghost btn-sm" onClick={() => resaAction(r.id, 'Refusée')}>Refuser</button>
                              </span>
                            ) : (
                              <span className="tiny">{r.status}</span>
                            )}
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        )}

        {tab === 'fiche' && (
          <div>
            <Header
              title="Ma fiche"
              sub={business ? 'Votre fiche est publiée et réservable sur Darsouk.' : 'Créez votre fiche pour apparaître dans la recherche et recevoir des réservations.'}
            />
            <BusinessEditor business={business} />
          </div>
        )}

        {tab === 'messages' && (
          <div>
            <Header title="Messagerie" sub="Échangez avec vos clients à propos de leurs réservations." />
            <Messenger threads={threads} />
          </div>
        )}

        {tab === 'avis' && (
          <div>
            <Header title="Avis" sub="Consultez et répondez aux avis de vos clients." />
            <Avis reviews={reviews} stats={reviewStats} bizName={bizName} />
          </div>
        )}

        {tab === 'stats' && (
          <div>
            <Header title="Statistiques" sub="Suivez la performance de votre établissement sur Darsouk." />
            <Stats />
          </div>
        )}

        {(tab === 'abo' || tab === 'set') && (
          <div>
            <Header title={tab === 'abo' ? 'Abonnement' : 'Paramètres'} />
            <div className="panel" style={{ textAlign: 'center', padding: 60 }}>
              <Icon name={tab === 'abo' ? 'card' : 'settings'} size={36} style={{ color: 'var(--faint)' }} />
              <h3 className="h3" style={{ marginTop: 14 }}>
                Section « {tab === 'abo' ? 'Abonnement' : 'Paramètres'} »
              </h3>
              <p className="body" style={{ marginTop: 6, maxWidth: 360, margin: '6px auto 0' }}>
                Cette section sera détaillée dans la prochaine itération du prototype.
              </p>
              {tab === 'abo' && (
                <button className="btn btn-red" style={{ marginTop: 18 }} onClick={() => go('pricing')}>
                  Voir les offres
                </button>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
