/* ===== Dashboard — Famille + Intervenant (autonome) ===== */

/* —————————————————————————————————————————————————————
   Purge de lancement officiel — efface les données démo persistées
   chez les utilisateurs ayant visité une version antérieure.
   Le flag empêche que la purge se rejoue après nettoyage.
   ————————————————————————————————————————————————————— */
(function ensureCleanLaunch() {
  try {
    // v2 — purge forcée des données démo (dépenses, modales, etc.)
    // ⚠️ Bumper la version (v3, v4…) si une nouvelle purge devient nécessaire.
    const FLAG = 'maisonsereine-launch-clean-v2';
    if (!localStorage.getItem(FLAG)) {
      ['maisonsereine-expenses', 'maisonsereine-welcome-seen',
       'maisonsereine-intervenant-onboard',
       'maisonsereine-launch-clean-v1' /* nettoyage de l'ancien drapeau */
      ].forEach(k => localStorage.removeItem(k));
      localStorage.setItem(FLAG, '1');
    }
  } catch (e) { /* localStorage indisponible — rien à faire */ }
})();

const DashboardPage = () => {
  const [view, setView] = React.useState('family'); // 'family' | 'intervenant'
  const [tab, setTab] = React.useState('home');
  const [showWelcome, setShowWelcome] = React.useState(() => {
    try { return !localStorage.getItem('maisonsereine-welcome-seen'); } catch (e) { return true; }
  });
  const closeWelcome = () => {
    try { localStorage.setItem('maisonsereine-welcome-seen', '1'); } catch (e) {}
    setShowWelcome(false);
  };
  const goToTeam = () => { closeWelcome(); setTab('team'); };
  return (
    <div style={{ minHeight: '100vh', background: 'var(--bg-2)' }}>
      <DashViewSwitch view={view} setView={setView} />
      {view === 'family' ? (
        <>
          <DashNav tab={tab} setTab={setTab} />
          <div style={{ padding: '32px 0' }}>
            <div className="container">
              {tab === 'home' && <DashHome />}
              {tab === 'planning' && <DashPlanning />}
              {tab === 'team' && <DashTeam />}
              {tab === 'messages' && <DashMessages />}
              {tab === 'billing' && <DashBilling />}
            </div>
          </div>
          {showWelcome && <WelcomeModal onDismiss={closeWelcome} onAction={goToTeam} />}
        </>
      ) : (
        <IntervenantDash />
      )}
    </div>
  );
};

/* --------- View switcher Famille/Intervenant --------- */
const DashViewSwitch = ({ view, setView }) => (
  <div style={{
    background: 'var(--bg)', borderBottom: '1px solid var(--line)',
    padding: '10px 0'
  }}>
    <div className="container row" style={{ gap: 8, justifyContent: 'center' }}>
      <div className="row" style={{ gap: 6, background: 'var(--bg-2)', padding: 4, borderRadius: 999, border: '1px solid var(--line)' }}>
        {[['family', 'Espace Famille'], ['intervenant', 'Espace Intervenant']].map(([k, l]) => {
          const on = view === k;
          return (
            <button key={k} onClick={() => setView(k)} style={{
              padding: '8px 18px', borderRadius: 999, border: 0,
              background: on ? 'var(--primary)' : 'transparent',
              color: on ? '#fff' : 'var(--ink-2)',
              fontSize: 13, fontWeight: 500, cursor: 'pointer', minHeight: 36
            }}>{l}</button>
          );
        })}
      </div>
    </div>
  </div>
);

/* --------- Store de dépenses (partagé entre onglets) --------- */
const EXPENSE_CATEGORIES = [
  { id: 'transport', label: 'Transport / essence', emoji: '🚗' },
  { id: 'fournitures', label: 'Fournitures & EPI', emoji: '🧤' },
  { id: 'formation', label: 'Formation continue', emoji: '📚' },
  { id: 'telecom', label: 'Téléphone / Internet', emoji: '📱' },
  { id: 'vetements', label: 'Vêtements de travail', emoji: '👕' },
  { id: 'sante', label: 'Assurances / santé', emoji: '🏥' },
  { id: 'autre', label: 'Autre', emoji: '📎' },
];
const useExpenses = () => {
  const [expenses, setExpenses] = React.useState(() => {
    try {
      const raw = localStorage.getItem('maisonsereine-expenses');
      if (raw) return JSON.parse(raw);
    } catch (e) {}
    // État initial vide — l'intervenant·e ajoute ses propres dépenses
    return [];
  });
  React.useEffect(() => {
    try { localStorage.setItem('maisonsereine-expenses', JSON.stringify(expenses)); } catch (e) {}
  }, [expenses]);
  const add = (e) => setExpenses(prev => [{ id: 'e' + Date.now(), ...e }, ...prev]);
  const remove = (id) => setExpenses(prev => prev.filter(e => e.id !== id));
  return { expenses, add, remove };
};

/* --------- Espace Intervenant (autonome) --------- */
const IntervenantDash = () => {
  // Onglets internes
  const [iTab, setITab] = React.useState('home');
  const expensesStore = useExpenses();
  // Modal onboarding au premier accès
  const [showOnboard, setShowOnboard] = React.useState(() => {
    try { return !localStorage.getItem('maisonsereine-intervenant-onboard'); } catch (e) { return true; }
  });
  const dismissOnboard = () => {
    try { localStorage.setItem('maisonsereine-intervenant-onboard', '1'); } catch (e) {}
    setShowOnboard(false);
  };

  return (
    <>
      <IntervenantTabs tab={iTab} setTab={setITab} />
      <div className="container" style={{ padding: '32px 16px' }}>
        {iTab === 'home' && <IntervenantHome />}
        {iTab === 'depenses' && <MesDepenses store={expensesStore} />}
        {iTab === 'rapports' && <RapportsFinanciers expenses={expensesStore.expenses} />}
        {iTab === 'statut' && <StatutPartenaire />}
      </div>
      {showOnboard && <OnboardingModal onDismiss={dismissOnboard} />}
    </>
  );
};

/* Tabs internes intervenant — header aligné sur DashNav (brand + onglets, sticky). */
const IntervenantTabs = ({ tab, setTab }) => {
  const tabs = [
    { id: 'home',    label: "Mon tableau de bord", icon: 'home' },
    { id: 'depenses',label: "Mes dépenses", icon: 'credit-card' },
    { id: 'rapports',label: "Rapports financiers", icon: 'credit-card' },
    { id: 'statut',  label: "Statut de Partenaire", icon: 'sparkle' },
  ];
  return (
    <header style={{ background: 'var(--surface)', borderBottom: '1px solid var(--line)', position: 'sticky', top: 0, zIndex: 20 }}>
      <div className="container" style={{ padding: '14px 32px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16 }}>
        <a className="brand" href="#home" style={{ flexShrink: 0 }}>
          <BrandLogo size={32} color="var(--primary)" />
          <span>Maison Sereine</span>
        </a>
        <nav className="row" style={{ gap: 4, flexShrink: 1, minWidth: 0, overflowX: 'auto' }}>
          {tabs.map(t => {
            const on = tab === t.id;
            return (
              <button key={t.id} onClick={() => setTab(t.id)} className="row"
                title={t.label}
                style={{
                  gap: 8, padding: '10px 16px', borderRadius: 999,
                  background: on ? 'var(--primary)' : 'transparent',
                  color: on ? '#fff' : 'var(--ink-2)',
                  border: 0, fontSize: 13, fontWeight: 500,
                  whiteSpace: 'nowrap', flexShrink: 0, minHeight: 40, cursor: 'pointer'
                }}>
                <Icon name={t.icon} size={14} /> {t.label}
              </button>
            );
          })}
        </nav>
      </div>
    </header>
  );
};

/* Vue principale intervenant (renommée) */
const IntervenantHome = () => {
  const days = ['Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam', 'Dim'];
  // Plage horaire étendue 08h00 → 20h00, en tranches de 30 minutes
  const slots = [
    '08:00','08:30','09:00','09:30','10:00','10:30',
    '11:00','11:30','12:00','12:30','13:00','13:30',
    '14:00','14:30','15:00','15:30','16:00','16:30',
    '17:00','17:30','18:00','18:30','19:00','19:30','20:00'
  ];
  // État initial vide — l'intervenant·e définit ses disponibilités manuellement
  const [avail, setAvail] = React.useState({});
  const toggle = (d, h) => setAvail(a => ({ ...a, [d+'_'+h]: !a[d+'_'+h] }));
  const activeCount = Object.values(avail).filter(Boolean).length;
  const heuresActives = activeCount * 0.5;

  return (
    <div style={{ display: 'grid', gap: 24 }}>
      {/* Header intervenant */}
      <div className="row" style={{ justifyContent: 'space-between', flexWrap: 'wrap', gap: 16 }}>
        <div>
          <div className="eyebrow" style={{ color: 'var(--accent-2)' }}>Espace Intervenant · Travailleur autonome</div>
          <h2 style={{ marginTop: 6, fontSize: 28 }}>Bienvenue dans votre espace.</h2>
          <p style={{ color: 'var(--ink-2)', marginTop: 4, fontSize: 14 }}>
            Définissez vos disponibilités par tranches de 30 minutes — de 8 h à 20 h, du lundi au dimanche.
          </p>
        </div>
      </div>

      {/* Compteurs CA */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }} className="ca-grid">
        <Card>
          <div style={{ fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--ink-3)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>
            Chiffre d'affaires brut · semaine
          </div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 36, color: 'var(--primary)', marginTop: 8, lineHeight: 1 }}>0,00 $</div>
          <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 6 }}>Aucune prestation facturée cette semaine</div>
        </Card>
        <Card>
          <div style={{ fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--ink-3)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>
            CA brut · mois en cours
          </div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 36, color: 'var(--primary)', marginTop: 8, lineHeight: 1 }}>0,00 $</div>
          <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 6 }}>Aucune heure facturée ce mois-ci</div>
        </Card>
        <Card>
          <div style={{ fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--ink-3)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>
            Heures dispo · semaine
          </div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 36, color: 'var(--accent-2)', marginTop: 8, lineHeight: 1 }}>{heuresActives} h</div>
          <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 6 }}>
            {activeCount === 0 ? "Sélectionnez vos tranches ci-dessous" : `${activeCount} tranche${activeCount > 1 ? 's' : ''} active${activeCount > 1 ? 's' : ''}`}
          </div>
        </Card>
      </div>

      {/* Bulle fiscale */}
      <div style={{
        background: 'var(--accent-soft)', border: '1px solid var(--accent)',
        borderRadius: 12, padding: '14px 16px',
        display: 'flex', gap: 12, alignItems: 'flex-start'
      }}>
        <div style={{
          width: 28, height: 28, borderRadius: 999, flexShrink: 0,
          background: 'var(--accent-2)', color: '#fff',
          display: 'flex', alignItems: 'center', justifyContent: 'center'
        }}>
          <Icon name="sparkle" size={14} />
        </div>
        <div style={{ fontSize: 13, color: 'var(--ink), lineHeight: 1.55' }}>
          <strong>Travailleur autonome.</strong> En tant que travailleur autonome,
          vous êtes responsable de vos déclarations fiscales. Maison Sereine vous fournit
          un <strong>récapitulatif annuel</strong> de vos paiements pour simplifier vos démarches.
        </div>
      </div>

      {/* Calendrier disponibilités */}
      <Card title="Mes disponibilités · cette semaine" action={
        <span style={{ fontSize: 12, color: 'var(--ink-3)' }}>08 h → 20 h · tranches de 30 min · cliquer pour activer</span>
      }>
        <div style={{ overflowX: 'auto', overflowY: 'auto', maxHeight: 560 }}>
          <div style={{ display: 'grid', gridTemplateColumns: '70px repeat(7, 1fr)', gap: 4, minWidth: 560 }}>
            <div></div>
            {days.map(d => (
              <div key={d} style={{ position: 'sticky', top: 0, background: 'var(--surface)', zIndex: 2, textAlign: 'center', fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ink-3)', padding: '6px 0', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{d}</div>
            ))}
            {slots.map(h => (
              <React.Fragment key={h}>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--ink-3)', padding: '4px 0', textAlign: 'right', paddingRight: 8 }}>{h}</div>
                {days.map(d => {
                  const on = !!avail[d+'_'+h];
                  return (
                    <button key={d+h} onClick={() => toggle(d, h)}
                      style={{
                        height: 26, borderRadius: 6,
                        background: on ? 'var(--primary)' : 'var(--bg-2)',
                        border: '1px solid ' + (on ? 'var(--primary)' : 'var(--line)'),
                        cursor: 'pointer', transition: 'all .15s ease', padding: 0
                      }}
                      aria-label={on ? 'Active' : 'Désactivée'}
                    />
                  );
                })}
              </React.Fragment>
            ))}
          </div>
        </div>
        <div className="row" style={{ gap: 16, marginTop: 16, fontSize: 12, color: 'var(--ink-3)' }}>
          <span className="row" style={{ gap: 6 }}><span style={{ width: 12, height: 12, background: 'var(--primary)', borderRadius: 3 }}/> Disponible</span>
          <span className="row" style={{ gap: 6 }}><span style={{ width: 12, height: 12, background: 'var(--bg-2)', border: '1px solid var(--line)', borderRadius: 3 }}/> Indisponible</span>
        </div>
      </Card>

      {/* Paramètres du profil → désormais intégrés dans « Statut de Partenaire » (onglet dédié). */}

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

/* --------- Welcome modal — Sécurité & Confiance (first sign-in) --------- */
const WelcomeModal = ({ onDismiss, onAction }) => {
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onDismiss(); };
    window.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = prev;
    };
  }, [onDismiss]);

  const pillars = [
    {
      icon: 'shield',
      t: "Protocole de Relève",
      d: "En cas d'empêchément d'un intervenant, on s'organise pour mobiliser une autre personne disponible dans le secteur. Vous êtes prévenu·e dès qu'on a une solution — ou avant, pour vous tenir au courant.",
    },
    {
      icon: 'heart',
      t: "Le Carnet de Liaison Numérique",
      d: "Suivez en temps réel le bien-être de votre proche (humeur, repas, médication) directement dans votre onglet Vue d'ensemble.",
    },
    {
      icon: 'lock',
      t: "Protection Loi 25",
      d: "Toutes les données de santé sont chiffrées et l'accès des étudiants est strictement limité à la durée de leur mission.",
    },
  ];

  return (
    <div
      role="dialog" aria-modal="true" aria-labelledby="welcome-title"
      style={{
        position: 'fixed', inset: 0, zIndex: 1000,
        background: 'rgba(28, 38, 34, 0.46)', backdropFilter: 'blur(6px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 24, animation: 'msFade .25s ease-out',
      }}
      onClick={onDismiss}
    >
      <style>{`
        @keyframes msFade { from { opacity: 0 } to { opacity: 1 } }
        @keyframes msRise { from { opacity: 0; transform: translateY(18px) } to { opacity: 1; transform: translateY(0) } }
      `}</style>
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          position: 'relative', width: '100%', maxWidth: 620,
          background: 'var(--bg-1, #F7F2EA)', borderRadius: 22,
          boxShadow: '0 40px 120px rgba(28,38,34,0.28)',
          padding: '56px 56px 44px', animation: 'msRise .32s ease-out',
          border: '1px solid var(--line)',
        }}
      >
        <button
          onClick={onDismiss}
          aria-label="Fermer"
          style={{
            position: 'absolute', top: 18, right: 18, width: 36, height: 36,
            borderRadius: 999, border: '1px solid var(--line)', background: 'transparent',
            color: 'var(--ink-3)', cursor: 'pointer', display: 'flex',
            alignItems: 'center', justifyContent: 'center',
          }}
        >
          <Icon name="close" size={16} />
        </button>

        <div className="eyebrow" style={{ color: 'var(--primary)' }}>Bienvenue chez Maison Sereine</div>
        <h2
          id="welcome-title"
          style={{
            fontFamily: 'var(--font-display)', fontSize: 34, lineHeight: 1.15,
            marginTop: 10, color: 'var(--ink)', maxWidth: 460,
          }}
        >
          Votre tranquillité d'esprit est notre priorité.
        </h2>
        <p style={{ color: 'var(--ink-2)', marginTop: 14, fontSize: 15, lineHeight: 1.55, maxWidth: 480 }}>
          Pour garantir un service d'excellence à votre proche, nous avons activé trois protocoles exclusifs :
        </p>

        <ul style={{ listStyle: 'none', padding: 0, margin: '28px 0 0', display: 'grid', gap: 18 }}>
          {pillars.map(p => (
            <li key={p.t} style={{ display: 'grid', gridTemplateColumns: '44px 1fr', gap: 16, alignItems: 'flex-start' }}>
              <div style={{
                width: 44, height: 44, borderRadius: 12,
                background: 'var(--primary-soft)', color: 'var(--primary)',
                display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
              }}>
                <Icon name={p.icon} size={20} />
              </div>
              <div>
                <div style={{ fontFamily: 'var(--font-display)', fontSize: 17, color: 'var(--ink)' }}>{p.t}</div>
                <div style={{ color: 'var(--ink-2)', fontSize: 14, lineHeight: 1.55, marginTop: 4 }}>{p.d}</div>
              </div>
            </li>
          ))}
        </ul>

        <div className="row" style={{ marginTop: 36, gap: 12, flexWrap: 'wrap' }}>
          <button className="btn btn-primary" onClick={onAction} style={{ padding: '13px 22px', fontSize: 15 }}>
            Découvrir mon équipe vérifiée <Icon name="arrow-right" size={15} />
          </button>
          <button className="btn btn-ghost" onClick={onDismiss} style={{ padding: '13px 18px', fontSize: 14 }}>
            Plus tard
          </button>
        </div>
      </div>
    </div>
  );
};

const DashNav = ({ tab, setTab }) => {
  const tabs = [
    { id: 'home',     label: "Vue d’ensemble", icon: 'home' },
    { id: 'planning', label: "Planning",        icon: 'calendar' },
    { id: 'team',     label: "Équipe",          icon: 'users' },
    { id: 'messages', label: "Messages",        icon: 'message' },
    { id: 'billing',  label: "Facturation",     icon: 'credit-card' },
  ];
  const [wide, setWide] = React.useState(typeof window !== 'undefined' ? window.innerWidth >= 1100 : true);
  React.useEffect(() => {
    const onR = () => setWide(window.innerWidth >= 1100);
    window.addEventListener('resize', onR);
    return () => window.removeEventListener('resize', onR);
  }, []);
  return (
    <header style={{ background: 'var(--surface)', borderBottom: '1px solid var(--line)', position: 'sticky', top: 0, zIndex: 20 }}>
      <div className="container" style={{ padding: '14px 32px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16 }}>
        <a className="brand" href="#home" style={{ flexShrink: 0 }}>
          <BrandLogo size={32} color="var(--primary)" />
          <span>Maison Sereine</span>
        </a>
        <nav className="row" style={{ gap: 2, flexShrink: 1, minWidth: 0, overflow: 'hidden' }}>
          {tabs.map(t => {
            const on = tab === t.id;
            return (
              <button key={t.id} onClick={() => setTab(t.id)} className="row"
                title={t.label}
                style={{
                  gap: 8, padding: wide ? '10px 14px' : '10px 12px', borderRadius: 999,
                  background: on ? 'var(--primary)' : 'transparent',
                  color: on ? '#fff' : 'var(--ink-2)',
                  border: 0, fontSize: 14, fontWeight: 500,
                  whiteSpace: 'nowrap', flexShrink: 0
                }}>
                <Icon name={t.icon} size={16} />{wide && t.label}
              </button>
            );
          })}
        </nav>
        <div className="row" style={{ gap: 10, flexShrink: 0 }}>
          <button style={{ width: 40, height: 40, borderRadius: '50%', background: 'var(--bg-2)', border: '1px solid var(--line)', position: 'relative', flexShrink: 0 }}>
            <Icon name="bell" size={16} />
            <span style={{ position: 'absolute', top: 8, right: 9, width: 8, height: 8, background: 'var(--accent)', borderRadius: 999, border: '2px solid var(--bg-2)' }}/>
          </button>
          <div className="row" style={{ gap: 8 }}>
            <div style={{ width: 36, height: 36, borderRadius: '50%', background: 'var(--primary-soft)', color: 'var(--primary)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <Icon name="user" size={18} />
            </div>
            {wide && (
              <div style={{ fontSize: 13, whiteSpace: 'nowrap' }}>
                <div style={{ fontWeight: 500 }}>Mon compte</div>
                <div style={{ color: 'var(--ink-3)', fontSize: 12 }}>Espace famille</div>
              </div>
            )}
          </div>
        </div>
      </div>
    </header>
  );
};

const Card = ({ children, style, title, action }) => (
  <section style={{
    background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 16, padding: 24,
    ...style
  }}>
    {(title || action) && (
      <div className="row" style={{ justifyContent: 'space-between', marginBottom: 18, alignItems: 'end', gap: 12, flexWrap: 'wrap' }}>
        {title && <div style={{ fontFamily: 'var(--font-display)', fontSize: 20, whiteSpace: 'nowrap' }}>{title}</div>}
        {action}
      </div>
    )}
    {children}
  </section>
);

/* --------- État vide réutilisable — modèle esthétique pour dashboards sans données --------- */
const EmptyState = ({ icon = 'sparkle', title, description, action, dense = false }) => (
  <div style={{
    padding: dense ? '28px 16px' : '44px 24px',
    textAlign: 'center', display: 'flex', flexDirection: 'column',
    alignItems: 'center', gap: 12
  }}>
    <div style={{
      width: 56, height: 56, borderRadius: 999,
      background: 'var(--bg-2)', color: 'var(--ink-3)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      border: '1px solid var(--line)'
    }}>
      <Icon name={icon} size={22} />
    </div>
    <div style={{ fontFamily: 'var(--font-display)', fontSize: 17, color: 'var(--ink)', marginTop: 4 }}>{title}</div>
    {description && (
      <div style={{ fontSize: 13.5, color: 'var(--ink-3)', maxWidth: 380, lineHeight: 1.55 }}>
        {description}
      </div>
    )}
    {action && <div style={{ marginTop: 6 }}>{action}</div>}
  </div>
);

/* --------- Protocole de Relève Prioritaire (carte interactive) --------- */
const ProtocoleReleve = () => {
  // Étapes simulées du protocole
  const STEPS = [
    { id: 'alert',    label: "Empiètement signalé",      icon: 'bell',   t: '14:02' },
    { id: 'notified', label: "Recherche en cours",        icon: 'users',  t: '14:04' },
    { id: 'approach', label: "Solution proposée",         icon: 'map-pin', t: '14:18' },
    { id: 'confirmed',label: "Remplaçant·e confirmé·e",    icon: 'check',  t: null },
  ];

  const [active, setActive] = React.useState(false);
  const [step, setStep] = React.useState(2);   // 0=alert, 1=notified, 2=approach, 3=confirmed
  const [elapsed, setElapsed] = React.useState(16); // minutes écoulées (simulation)

  // Simulation : avance d'une étape toutes les 8s quand actif (démo)
  React.useEffect(() => {
    if (!active) return;
    const id = setInterval(() => {
      setElapsed(e => e + 1);
    }, 60000);
    return () => clearInterval(id);
  }, [active]);

  if (!active) {
    // Vue "tout va bien" — un mini-statut rassurant
    return (
      <Card title="Protocole de Relève">
        <div className="row" style={{
          gap: 12, padding: '12px 14px',
          background: 'var(--primary-soft)', borderRadius: 10,
          border: '1px solid var(--primary)'
        }}>
          <div style={{
            width: 32, height: 32, borderRadius: 999,
            background: 'var(--primary)', color: '#fff',
            display: 'flex', alignItems: 'center', justifyContent: 'center'
          }}>
            <Icon name="check" size={16} />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14, fontWeight: 500 }}>Aucun incident en cours</div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>
              Aucune prestation à surveiller pour le moment.
            </div>
          </div>
        </div>
        <button
          className="btn btn-ghost"
          onClick={() => setActive(true)}
          style={{ width: '100%', marginTop: 12, padding: '10px 14px', fontSize: 13, minHeight: 40 }}
        >
          Aperçu du protocole en action
        </button>
      </Card>
    );
  }

  // Recherche encore active si pas confirmée
  const stillSearching = step < 3;
  const past30 = stillSearching && elapsed >= 30;

  return (
    <Card title={
      <span className="row" style={{ gap: 10 }}>
        <span style={{
          width: 10, height: 10, borderRadius: 999,
          background: stillSearching ? 'var(--accent)' : 'var(--good)',
          boxShadow: stillSearching ? '0 0 0 4px rgba(201,110,74,0.18)' : '0 0 0 4px rgba(91,127,78,0.18)',
          animation: stillSearching ? 'pulse 1.6s ease-in-out infinite' : 'none'
        }}/>
        Protocole de Relève
      </span>
    } action={
      <span className="chip" style={{
        background: stillSearching ? 'var(--accent-soft)' : 'var(--primary-soft)',
        color: stillSearching ? 'var(--accent-2)' : 'var(--primary)',
        border: 'none', fontWeight: 500, fontSize: 12
      }}>
        {stillSearching ? 'Recherche active' : 'Confirmée'}
      </span>
    }>
      <style>{`
        @keyframes pulse {
          0%,100% { transform: scale(1); opacity: 1; }
          50%     { transform: scale(1.18); opacity: 0.7; }
        }
        @keyframes shimmer {
          0% { background-position: -200% 0; }
          100% { background-position: 200% 0; }
        }
      `}</style>

      {/* Contexte */}
      <div style={{ marginBottom: 16, fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.5 }}>
        <strong>Un·e intervenant·e a signalé un empêchement</strong> pour la prochaine
        prestation. Notre coordination clinique mobilise les profils disponibles dans
        votre secteur — vous serez prévenu·e dès qu'une solution est confirmée.
      </div>

      {/* Barre de progression */}
      <div style={{ position: 'relative', marginBottom: 18 }}>
        <div style={{
          height: 6, background: 'var(--bg-2)', borderRadius: 999, overflow: 'hidden',
          border: '1px solid var(--line)'
        }}>
          <div style={{
            height: '100%',
            width: `${((step + 1) / STEPS.length) * 100}%`,
            background: stillSearching
              ? 'linear-gradient(90deg, var(--accent) 0%, var(--accent-2) 50%, var(--accent) 100%)'
              : 'var(--good)',
            backgroundSize: '200% 100%',
            animation: stillSearching ? 'shimmer 2s linear infinite' : 'none',
            transition: 'width .4s ease',
            borderRadius: 999
          }}/>
        </div>
      </div>

      {/* Étapes */}
      <ol style={{ listStyle: 'none', padding: 0, margin: '0 0 16px', display: 'grid', gap: 10 }}>
        {STEPS.map((s, i) => {
          const done = i < step;
          const current = i === step && stillSearching;
          const pending = i > step;
          const finalDone = i === step && !stillSearching;
          return (
            <li key={s.id} style={{
              display: 'grid', gridTemplateColumns: '28px 1fr auto', gap: 12,
              alignItems: 'center',
              opacity: pending ? 0.45 : 1
            }}>
              <div style={{
                width: 28, height: 28, borderRadius: 999, flexShrink: 0,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                background: done || finalDone
                  ? 'var(--primary)'
                  : current
                    ? 'var(--accent)'
                    : 'var(--bg-2)',
                color: (done || finalDone || current) ? '#fff' : 'var(--ink-3)',
                border: '1px solid ' + (
                  done || finalDone ? 'var(--primary)' :
                  current ? 'var(--accent)' : 'var(--line)'
                ),
                boxShadow: current ? '0 0 0 4px rgba(201,110,74,0.16)' : 'none',
              }}>
                {(done || finalDone) ? <Icon name="check" size={14} /> : <Icon name={s.icon} size={13} />}
              </div>
              <div>
                <div style={{ fontSize: 14, fontWeight: current ? 500 : 400, color: 'var(--ink)' }}>
                  {s.label}
                </div>
                {current && (
                  <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 2 }}>
                    Recherche dans votre secteur — confirmation imminente.
                  </div>
                )}
              </div>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ink-3)' }}>
                {s.t || '—'}
              </div>
            </li>
          );
        })}
      </ol>

      {/* Message d'attente si recherche prend du temps */}
      {past30 && (
        <div style={{
          padding: '12px 14px', background: 'var(--bg-2)',
          border: '1px solid var(--line)', borderRadius: 10,
          marginBottom: 12, fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.5
        }}>
          <div className="row" style={{ gap: 8, marginBottom: 4 }}>
            <Icon name="message" size={14} style={{ color: 'var(--accent-2)' }} />
            <strong style={{ fontSize: 12, color: 'var(--ink)' }}>Mise à jour · {elapsed} min</strong>
          </div>
          « La recherche est toujours en cours dans votre secteur. On vous tient
          au courant dès qu'on a une solution. »
        </div>
      )}

      {/* Geste commercial — seulement si la mission ne peut pas être honorée */}
      <div style={{
        padding: 14, background: 'var(--accent-soft)',
        border: '1px solid var(--accent)', borderRadius: 10
      }}>
        <div className="row" style={{ gap: 8, marginBottom: 6 }}>
          <Icon name="shield" size={14} style={{ color: 'var(--accent-2)' }} />
          <strong style={{ fontSize: 13, color: 'var(--accent-2)' }}>Engagement Maison Sereine</strong>
        </div>
        <div style={{ fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.55 }}>
          Si malgré nos efforts la séance ne peut être honorée, elle ne vous est
          <strong> pas facturée</strong>. C'est une obligation de moyens, pas de résultat.
        </div>
      </div>

      <button
        className="btn btn-ghost"
        onClick={() => setActive(false)}
        style={{ width: '100%', marginTop: 12, padding: '10px 14px', fontSize: 13, minHeight: 40 }}
      >
        Fermer l'aperçu
      </button>

      <p style={{
        marginTop: 12, fontSize: 11, color: 'var(--ink-3)',
        lineHeight: 1.5, fontStyle: 'italic'
      }}>
        Maison Sereine déploie tous les moyens pour assurer un remplacement —
        obligation de moyens, non de résultat.
      </p>
    </Card>
  );
};

/* --------- Home / overview --------- */
const DashHome = () => {
  const today = new Date().toLocaleDateString('fr-CA', {
    weekday: 'long', day: 'numeric', month: 'long'
  });
  const fmtToday = today.charAt(0).toUpperCase() + today.slice(1);
  return (
  <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 24 }}>
    <div style={{ display: 'grid', gap: 24 }}>
      <Card style={{ background: 'var(--primary)', color: '#fff', border: 0 }}>
          <div className="row" style={{ justifyContent: 'space-between', alignItems: 'start', gap: 16, flexWrap: 'wrap' }}>
          <div style={{ flex: '1 1 280px' }}>
            <div className="eyebrow" style={{ color: '#BCCCC3' }}>{fmtToday}</div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 36, marginTop: 6, lineHeight: 1.1 }}>
              Bienvenue dans votre espace famille.
            </div>
            <p style={{ color: '#BCCCC3', marginTop: 12, maxWidth: 480 }}>
              Aucune prestation n'est encore planifiée. Réservez une première visite
              pour activer votre tableau de bord — coordination, notes de suivi et
              facturation s'afficheront ici dès le démarrage.
            </p>
            <a href="#booking" className="btn btn-primary" style={{
              marginTop: 18, background: 'var(--accent)', color: '#fff'
            }}>
              Réserver une première visite <Icon name="arrow-right" size={15} />
            </a>
          </div>
          <div className="chip" style={{ background: 'rgba(255,255,255,0.1)', color: '#fff', border: '1px solid rgba(255,255,255,0.2)', whiteSpace: 'nowrap', flexShrink: 0 }}>
            <span style={{ width: 6, height: 6, borderRadius: 999, background: '#F4D8B8', display: 'inline-block', marginRight: 6 }} />
            En attente de la première prestation
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginTop: 32 }}>
          {[
            ['Visites cette semaine', '—'],
            ['Heures ce mois', '—'],
            ['Facturé', '0,00 $'],
            ['Crédit CMD estimé', '0,00 $'],
          ].map(([k, v]) => (
            <div key={k}>
              <div style={{ fontSize: 12, color: '#BCCCC3', textTransform: 'uppercase', letterSpacing: '.1em' }}>{k}</div>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 24, marginTop: 4, opacity: 0.85 }}>{v}</div>
            </div>
          ))}
        </div>
      </Card>

      <Card title="Aujourd'hui" action={<a href="#dashboard" style={{ fontSize: 14 }}>Voir le planning →</a>}>
        <EmptyState
          icon="calendar"
          title="Aucune prestation prévue aujourd'hui"
          description="Dès qu'une visite sera planifiée, vous la retrouverez ici avec son heure, son intervenant·e et son statut en temps réel."
        />
      </Card>

      <Card title="Notes de suivi" action={<span className="row" style={{ gap: 6, fontSize: 12, color: 'var(--ink-3)' }}><Icon name="shield" size={12} /> Chiffré · Loi 25</span>}>
        <EmptyState
          icon="heart"
          title="Aucune note de suivi pour le moment"
          description="Après chaque visite, votre intervenant·e consigne ici humeur, médication, alimentation et observations. L'historique chiffré reste accessible aux membres autorisés de votre famille."
        />
      </Card>

      <Card title="Journal des visites" action={<span style={{ fontSize: 14, color: 'var(--ink-3)' }}>Historique vide</span>}>
        <EmptyState
          icon="message"
          title="Le journal s'enrichira après la première visite"
          description="Comptes-rendus détaillés, photos partagées avec votre consentement et messages de votre intervenant·e apparaîtront chronologiquement dans cette section."
        />
      </Card>
    </div>

    <div style={{ display: 'grid', gap: 24, alignContent: 'start' }}>
      <ProtocoleReleve />
      <Card title="Actions rapides">
        <div style={{ display: 'grid', gap: 8 }}>
          {[
            ['Réserver une visite', 'plus', '#booking'],
            ['Contacter la coordination', 'message', 'mailto:contact@maisonsereine.ca'],
            ['Inviter un proche', 'users', '#dashboard'],
            ['Modifier le planning', 'calendar', '#dashboard'],
          ].map(([t, i, href]) => (
            <a key={t} href={href} className="row" style={{
              width: '100%', padding: '14px 16px', border: '1px solid var(--line)',
              background: 'var(--surface)', borderRadius: 10, justifyContent: 'space-between',
              fontFamily: 'inherit', fontSize: 15, color: 'var(--ink)', textDecoration: 'none'
            }}>
              <span className="row" style={{ gap: 12 }}>
                <Icon name={i} size={18} style={{ color: 'var(--primary)' }} /> {t}
              </span>
              <Icon name="chevron-right" size={16} style={{ color: 'var(--ink-3)' }} />
            </a>
          ))}
        </div>
      </Card>

      <Card title="Intervenant·e associé·e">
        <EmptyState
          dense
          icon="user"
          title="Aucun·e intervenant·e jumelé·e"
          description="Une fois la réservation confirmée, notre coordination clinique vous présentera le profil vérifié qui correspond le mieux aux besoins de votre proche."
        />
      </Card>

      <Card title="Bon à savoir">
        <div style={{ display: 'grid', gap: 14, fontSize: 14 }}>
          <div className="row" style={{ gap: 12, alignItems: 'start' }}>
            <div style={{ width: 32, height: 32, borderRadius: 8, background: 'var(--accent-soft)', color: 'var(--accent-2)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <Icon name="sparkle" size={16} />
            </div>
            <div>
              <div style={{ fontWeight: 500 }}>Crédit d'impôt CMD 2026</div>
              <div style={{ color: 'var(--ink-3)' }}>Jusqu'à 40 % récupérable via l'annexe J (Revenu Québec).</div>
            </div>
          </div>
          <div className="row" style={{ gap: 12, alignItems: 'start' }}>
            <div style={{ width: 32, height: 32, borderRadius: 8, background: 'var(--primary-soft)', color: 'var(--primary)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <Icon name="shield" size={16} />
            </div>
            <div>
              <div style={{ fontWeight: 500 }}>Programme SAPA · CIUSSS</div>
              <div style={{ color: 'var(--ink-3)' }}>Demande d'évaluation pour soutien à domicile complémentaire.</div>
            </div>
          </div>
        </div>
      </Card>
    </div>
  </div>
  );
};

const Entry = ({ who, time, text, photos, mood }) => (
  <div style={{ display: 'grid', gridTemplateColumns: '40px 1fr', gap: 14 }}>
    <div style={{ width: 40, height: 40, borderRadius: '50%', background: 'var(--accent-soft)', color: 'var(--accent-2)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 600 }}>
      {who.split(' ')[0][0]}
    </div>
    <div>
      <div className="row" style={{ justifyContent: 'space-between' }}>
        <span style={{ fontWeight: 500 }}>{who} <span style={{ fontSize: 18, marginLeft: 6 }}>{mood}</span></span>
        <span style={{ fontSize: 13, color: 'var(--ink-3)' }}>{time}</span>
      </div>
      <p style={{ color: 'var(--ink-2)', marginTop: 4 }}>{text}</p>
      {photos > 0 && (
        <div className="row" style={{ gap: 8, marginTop: 10 }}>
          {Array.from({length: photos}).map((_, i) => (
            <div key={i} className="ph" style={{ width: 84, height: 84, padding: 0, fontSize: 0 }} />
          ))}
        </div>
      )}
    </div>
  </div>
);

/* --------- Planning --------- */
const DashPlanning = () => {
  // Plage horaire 08h–20h pour cohérence avec le calendrier intervenant
  const hours = ['08','10','12','14','16','18','20'];
  // Semaine courante calculée dynamiquement (lundi → dimanche)
  const today = new Date();
  const dayOfWeek = (today.getDay() + 6) % 7; // 0 = lundi
  const monday = new Date(today);
  monday.setDate(today.getDate() - dayOfWeek);
  const weekDays = Array.from({ length: 7 }, (_, i) => {
    const d = new Date(monday);
    d.setDate(monday.getDate() + i);
    const lbl = d.toLocaleDateString('fr-CA', { weekday: 'short', day: 'numeric' });
    return lbl.charAt(0).toUpperCase() + lbl.slice(1);
  });
  const events = []; // Aucune prestation planifiée — état vide professionnel
  const weekRangeLabel = (() => {
    const last = new Date(monday); last.setDate(monday.getDate() + 6);
    const opts = { day: 'numeric', month: 'long' };
    return `Semaine du ${monday.toLocaleDateString('fr-CA', { day: 'numeric' })} au ${last.toLocaleDateString('fr-CA', opts)}`;
  })();
  return (
    <Card title={weekRangeLabel} action={
      <div className="row" style={{ gap: 8 }}>
        <button className="btn btn-ghost" style={{ padding: '8px 14px', minHeight: 36, fontSize: 14 }}><Icon name="arrow-left" size={14} /></button>
        <button className="btn btn-ghost" style={{ padding: '8px 14px', minHeight: 36, fontSize: 14 }}>Aujourd'hui</button>
        <button className="btn btn-ghost" style={{ padding: '8px 14px', minHeight: 36, fontSize: 14 }}><Icon name="arrow-right" size={14} /></button>
        <a href="#booking" className="btn btn-primary" style={{ padding: '8px 16px', minHeight: 36, fontSize: 14 }}><Icon name="plus" size={14} /> Planifier une visite</a>
      </div>
    }>
      {events.length === 0 ? (
        <EmptyState
          icon="calendar"
          title="Aucune prestation planifiée cette semaine"
          description="Réservez votre première visite pour voir s'afficher ici votre planning hebdomadaire avec l'horaire de chaque prestation, l'intervenant·e assigné·e et les rendez-vous médicaux."
          action={
            <a href="#booking" className="btn btn-primary" style={{ marginTop: 4 }}>
              Planifier une visite <Icon name="arrow-right" size={15} />
            </a>
          }
        />
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: '70px repeat(7, 1fr)', fontSize: 13 }}>
          <div />
          {weekDays.map(d => (
            <div key={d} style={{ padding: '0 6px 10px', textAlign: 'center', fontWeight: 500, color: 'var(--ink-2)' }}>{d}</div>
          ))}
          {hours.map((h, hi) => (
            <React.Fragment key={h}>
              <div style={{ borderTop: '1px solid var(--line)', padding: '10px 6px 0', color: 'var(--ink-3)', fontFamily: 'var(--font-mono)', fontSize: 11 }}>{h}:00</div>
              {weekDays.map((d, di) => {
                const ev = events.find(e => e.day === di && e.h === h);
                return (
                  <div key={d+h} style={{ borderTop: '1px solid var(--line)', borderLeft: di === 0 ? '1px solid var(--line)' : 0, borderRight: '1px solid var(--line)', minHeight: 64, padding: 4, position: 'relative' }}>
                    {ev && (
                      <div style={{
                        background: ev.color, color: '#fff', borderRadius: 8, padding: '8px 10px',
                        fontSize: 12, height: ev.len * 64 - 8, overflow: 'hidden', position: 'relative', zIndex: 1
                      }}>
                        <div style={{ fontWeight: 500 }}>{ev.t}</div>
                        <div style={{ opacity: 0.8, marginTop: 2 }}>{ev.who || 'Intervenant·e à confirmer'}</div>
                      </div>
                    )}
                  </div>
                );
              })}
            </React.Fragment>
          ))}
        </div>
      )}
    </Card>
  );
};

/* --------- Team --------- */
const DashTeam = () => {
  const team = []; // Équipe constituée après le jumelage avec la coordination clinique
  const proches = []; // Aucun proche connecté tant que vous n'avez pas envoyé d'invitation
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 24 }}>
      <Card title="Votre équipe" action={
        <a href="#booking" className="btn btn-ghost" style={{ padding: '8px 14px', minHeight: 36, fontSize: 14 }}>
          <Icon name="plus" size={14} /> Réserver une visite
        </a>
      }>
        {team.length === 0 ? (
          <EmptyState
            icon="users"
            title="Votre équipe se constitue après la première réservation"
            description="Une fois la prestation confirmée, vous verrez ici votre intervenant·e principal·e, son ou sa remplaçant·e prioritaire et, le cas échéant, votre médecin de famille — chacun avec ses certifications vérifiées."
            action={
              <a href="#booking" className="btn btn-primary" style={{ marginTop: 4 }}>
                Démarrer la réservation <Icon name="arrow-right" size={15} />
              </a>
            }
          />
        ) : (
          <div style={{ display: 'grid', gap: 12 }}>
            {team.map((p, idx) => (
              <div key={p.name} style={{ border: '1px solid var(--line)', borderRadius: 12, padding: 18, display: 'grid', gap: 14 }}>
                <div style={{ display: 'grid', gridTemplateColumns: '56px 1fr auto', gap: 18, alignItems: 'center' }}>
                  <div style={{
                    width: 56, height: 56, borderRadius: '50%', background: 'var(--accent-soft)',
                    color: 'var(--accent-2)', display: 'flex', alignItems: 'center', justifyContent: 'center'
                  }}>
                    <Icon name="user" size={22} />
                  </div>
                  <div>
                    <div className="row" style={{ gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
                      <div style={{ fontFamily: 'var(--font-display)', fontSize: 19 }}>{p.name}</div>
                      {p.verified && (
                        <span className="row" style={{
                          gap: 4, padding: '2px 8px', borderRadius: 999,
                          background: 'var(--primary-soft)', color: 'var(--primary)',
                          border: '1px solid var(--primary)', fontSize: 11, fontWeight: 500
                        }}>
                          <Icon name="shield" size={11} /> Vérifié Sécurité
                        </span>
                      )}
                    </div>
                    <div style={{ fontSize: 13, color: 'var(--ink-3)' }}>{p.role} · {p.avail}</div>
                  </div>
                  <button className="btn btn-ghost" style={{ padding: '8px 14px', minHeight: 36, fontSize: 14 }}><Icon name="message" size={14} /></button>
                </div>
              </div>
            ))}
          </div>
        )}
      </Card>

      <Card title="Proches connectés" action={
        <a href="mailto:contact@maisonsereine.ca" style={{ fontSize: 13 }}>Inviter →</a>
      }>
        {proches.length === 0 ? (
          <EmptyState
            dense
            icon="users"
            title="Aucun proche connecté pour l'instant"
            description="Invitez les membres de votre famille pour qu'ils puissent suivre les visites, lire les comptes-rendus et recevoir les messages — avec un niveau d'accès que vous contrôlez."
            action={
              <a href="mailto:contact@maisonsereine.ca" className="btn btn-ghost" style={{ marginTop: 4 }}>
                <Icon name="plus" size={14} /> Envoyer une invitation
              </a>
            }
          />
        ) : (
          <>
            {proches.map(p => (
              <div key={p.name} className="row" style={{ padding: '10px 0', borderTop: '1px solid var(--line)', gap: 12 }}>
                <div style={{ width: 36, height: 36, borderRadius: '50%', background: 'var(--primary-soft)', color: 'var(--primary)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <Icon name="user" size={16} />
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 500, fontSize: 14 }}>{p.name}</div>
                  <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{p.role}</div>
                </div>
              </div>
            ))}
            <a href="mailto:contact@maisonsereine.ca" className="btn btn-ghost" style={{ width: '100%', marginTop: 14, justifyContent: 'center' }}>
              <Icon name="plus" size={14} /> Inviter un proche
            </a>
          </>
        )}
      </Card>
    </div>
  );
};

/* --------- Messages --------- */
const DashMessages = () => {
  const conversations = []; // Aucune conversation tant que la première prestation n'est pas confirmée
  const activeThread = null;
  return (
  <div style={{ display: 'grid', gridTemplateColumns: '320px 1fr', gap: 24 }}>
    <Card style={{ padding: 0, overflow: 'hidden' }}>
      <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--line)' }}>
        <div style={{ fontFamily: 'var(--font-display)', fontSize: 20 }}>Conversations</div>
      </div>
      {conversations.length === 0 ? (
        <EmptyState
          dense
          icon="message"
          title="Aucune conversation"
          description="Les échanges avec votre intervenant·e et notre coordination s'afficheront ici, en temps réel."
        />
      ) : (
        conversations.map((m, i) => (
          <div key={i} className="row" style={{ padding: 18, gap: 12, borderBottom: '1px solid var(--line)', background: m.active ? 'var(--bg-2)' : 'transparent' }}>
            <div style={{ width: 42, height: 42, borderRadius: '50%', background: 'var(--accent-soft)', color: 'var(--accent-2)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon name="user" size={18} />
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="row" style={{ justifyContent: 'space-between' }}>
                <span style={{ fontWeight: 500, fontSize: 14 }}>{m.who}</span>
                <span style={{ fontSize: 12, color: 'var(--ink-3)' }}>{m.time}</span>
              </div>
              <div style={{ fontSize: 13, color: 'var(--ink-3)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{m.last}</div>
            </div>
            {m.unread && <span style={{ width: 8, height: 8, background: 'var(--accent)', borderRadius: 999 }} />}
          </div>
        ))
      )}
    </Card>
    <Card style={{ padding: 0, display: 'flex', flexDirection: 'column', minHeight: 520 }}>
      {activeThread ? (
        <>
          <div className="row" style={{ padding: 20, borderBottom: '1px solid var(--line)', justifyContent: 'space-between' }}>
            <div className="row" style={{ gap: 12 }}>
              <div style={{ width: 42, height: 42, borderRadius: '50%', background: 'var(--accent-soft)' }} />
              <div>
                <div style={{ fontFamily: 'var(--font-display)', fontSize: 18 }}>{activeThread.who}</div>
                <div style={{ fontSize: 12, color: 'var(--good)' }}>● En ligne</div>
              </div>
            </div>
            <button className="btn btn-ghost" style={{ padding: '8px 14px', minHeight: 36, fontSize: 14 }}><Icon name="phone" size={14} /> Appeler</button>
          </div>
          <div style={{ padding: 20, flex: 1 }} />
        </>
      ) : (
        <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 32 }}>
          <EmptyState
            icon="message"
            title="Sélectionnez une conversation"
            description="Une fois votre première prestation activée, votre intervenant·e pourra vous envoyer ici des comptes-rendus, des photos partagées et des messages — toujours sous protocole chiffré (Loi 25)."
            action={
              <a href="mailto:contact@maisonsereine.ca" className="btn btn-ghost">
                <Icon name="mail" size={14} /> Écrire à la coordination
              </a>
            }
          />
        </div>
      )}
    </Card>
  </div>
  );
};

const Bubble = ({ side, children }) => (
  <div style={{
    alignSelf: side === 'me' ? 'flex-end' : 'flex-start',
    maxWidth: '70%',
    padding: '12px 16px',
    borderRadius: side === 'me' ? '16px 16px 4px 16px' : '16px 16px 16px 4px',
    background: side === 'me' ? 'var(--primary)' : 'var(--bg-2)',
    color: side === 'me' ? '#fff' : 'var(--ink)',
    fontSize: 15, lineHeight: 1.5,
    justifySelf: side === 'me' ? 'end' : 'start'
  }}>{children}</div>
);

/* --------- Billing --------- */
const DashBilling = () => {
  const invoices = []; // Aucune facture tant que la première prestation n'a pas eu lieu
  const paymentMethod = null; // Aucun moyen de paiement enregistré au lancement
  return (
  <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 24 }}>
    <Card title="Historique des factures" action={
      <button
        className="btn btn-ghost"
        style={{ padding: '8px 14px', minHeight: 36, fontSize: 14, opacity: invoices.length === 0 ? 0.45 : 1 }}
        disabled={invoices.length === 0}
      >
        <Icon name="download" size={14} /> Télécharger tout
      </button>
    }>
      {invoices.length === 0 ? (
        <EmptyState
          icon="credit-card"
          title="Aucune facture émise pour l'instant"
          description="Après chaque prestation, votre facture détaillée — montant facturé, part admissible au crédit d'impôt CMD et coût effectif estimé — s'ajoutera automatiquement à cet historique."
          action={
            <a href="#booking" className="btn btn-primary" style={{ marginTop: 4 }}>
              Réserver ma première visite <Icon name="arrow-right" size={15} />
            </a>
          }
        />
      ) : (
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 14 }}>
          <thead>
            <tr style={{ textAlign: 'left', color: 'var(--ink-3)', fontWeight: 500, fontSize: 12, textTransform: 'uppercase', letterSpacing: '.08em' }}>
              <th style={{ padding: '14px 0', borderBottom: '1px solid var(--line)' }}>Période</th>
              <th style={{ padding: '14px 0', borderBottom: '1px solid var(--line)' }}>Heures</th>
              <th style={{ padding: '14px 0', borderBottom: '1px solid var(--line)' }}>Facturé</th>
              <th style={{ padding: '14px 0', borderBottom: '1px solid var(--line)' }}>Coût effectif*</th>
              <th style={{ padding: '14px 0', borderBottom: '1px solid var(--line)' }}>Statut</th>
              <th style={{ padding: '14px 0', borderBottom: '1px solid var(--line)' }}></th>
            </tr>
          </thead>
          <tbody>
            {invoices.map((row, i) => (
              <tr key={i}>
                {row.slice(0, 4).map((c, j) => (
                  <td key={j} style={{ padding: '18px 0', borderBottom: '1px solid var(--line)' }}>{c}</td>
                ))}
                <td style={{ padding: '18px 0', borderBottom: '1px solid var(--line)' }}>
                  <span className="chip" style={{ color: row[5], borderColor: 'currentColor' }}>{row[4]}</span>
                </td>
                <td style={{ padding: '18px 0', borderBottom: '1px solid var(--line)', textAlign: 'right' }}>
                  <a>PDF →</a>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      )}
      <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 12 }}>
        * Coût effectif estimé après crédit d'impôt CMD (taux 2026 : 40 %). Montant final selon revenu familial et annexe J.
      </div>
    </Card>

    <div style={{ display: 'grid', gap: 24, alignContent: 'start' }}>
      <Card title="Factures & crédit d'impôt CMD">
        <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.6 }}>
          Vous payez la totalité de chaque facture. Un récapitulatif annuel détaillé vous sera transmis en janvier — à conserver et à joindre à l'<strong>annexe J</strong> de votre déclaration pour récupérer jusqu'à 40 % via le crédit d'impôt pour maintien à domicile des aînés (CMD).
        </div>
        <div className="row" style={{ marginTop: 16, justifyContent: 'space-between', color: 'var(--ink-3)' }}>
          <span>Récapitulatif annuel</span>
          <span style={{ fontSize: 13 }}>Disponible en janvier</span>
        </div>
      </Card>
      <Card title="Moyen de paiement">
        {paymentMethod ? (
          <div className="row" style={{ gap: 14 }}>
            <div style={{ width: 48, height: 32, borderRadius: 6, background: 'var(--ink)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 600, letterSpacing: '.1em' }}>VISA</div>
            <div>
              <div style={{ fontWeight: 500 }}>•••• {paymentMethod.last4}</div>
              <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>Expire {paymentMethod.exp}</div>
            </div>
          </div>
        ) : (
          <EmptyState
            dense
            icon="credit-card"
            title="Aucune carte enregistrée"
            description="Vous ajouterez votre moyen de paiement à l'étape Paiement de votre première réservation."
            action={
              <a href="#booking" className="btn btn-ghost" style={{ marginTop: 4 }}>
                <Icon name="plus" size={14} /> Ajouter au moment de la réservation
              </a>
            }
          />
        )}
      </Card>
      <Card title="Aides & dispositifs">
        {[
          ['SAPA — CIUSSS Capitale-Nationale', 'À évaluer'],
          ['Assurance privée',                  'À renseigner'],
          ['Chèque emploi-service',             "À activer si admissible"],
        ].map(([k, v]) => (
          <div key={k} className="row" style={{ padding: '12px 0', borderTop: '1px solid var(--line)', justifyContent: 'space-between' }}>
            <span style={{ fontSize: 14 }}>{k}</span>
            <span style={{ fontSize: 13, color: 'var(--ink-3)' }}>{v}</span>
          </div>
        ))}
      </Card>
    </div>
  </div>
  );
};

/* --------- Mes Dépenses (intervenant autonome) --------- */
const MesDepenses = ({ store }) => {
  const { expenses, add, remove } = store;
  const [showForm, setShowForm] = React.useState(false);
  const today = new Date().toISOString().slice(0, 10);
  const [form, setForm] = React.useState({ date: today, cat: 'transport', amount: '', desc: '', receipt: null });
  const fileRef = React.useRef(null);
  const fmt = (n) => Number(n).toLocaleString('fr-CA', { minimumFractionDigits: 2, maximumFractionDigits: 2 });

  // Filtre période
  const [period, setPeriod] = React.useState('month'); // 'month' | 'year'
  const now = new Date();
  const ym = `${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,'0')}`;
  const visible = expenses.filter(e => period === 'year' ? e.date.startsWith(String(now.getFullYear())) : e.date.startsWith(ym));
  const totalVisible = visible.reduce((s, e) => s + Number(e.amount || 0), 0);
  const totalYear = expenses.filter(e => e.date.startsWith(String(now.getFullYear()))).reduce((s, e) => s + Number(e.amount || 0), 0);
  const totalMonth = expenses.filter(e => e.date.startsWith(ym)).reduce((s, e) => s + Number(e.amount || 0), 0);

  // Totaux par catégorie (pour la période visible)
  const byCat = {};
  visible.forEach(e => { byCat[e.cat] = (byCat[e.cat] || 0) + Number(e.amount || 0); });

  const handleFile = (file) => {
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (ev) => setForm(f => ({ ...f, receipt: { name: file.name, dataUrl: ev.target.result } }));
    reader.readAsDataURL(file);
  };
  const submit = (e) => {
    e.preventDefault();
    if (!form.amount || isNaN(Number(form.amount))) return;
    add({ ...form, amount: Number(form.amount) });
    setForm({ date: today, cat: 'transport', amount: '', desc: '', receipt: null });
    setShowForm(false);
  };

  // Revenus de référence (aucun historique à l'amorçage du compte)
  const REVENUS_BRUTS = 0;
  const revenuImposable = Math.max(0, REVENUS_BRUTS - totalYear);

  return (
    <div style={{ display: 'grid', gap: 20, maxWidth: 920, margin: '0 auto' }}>
      {/* Header style banking */}
      <div className="row" style={{ justifyContent: 'space-between', alignItems: 'flex-end', flexWrap: 'wrap', gap: 14 }}>
        <div>
          <div className="eyebrow" style={{ color: 'var(--accent-2)' }}>Mes dépenses</div>
          <h2 style={{ fontSize: 28, marginTop: 6 }}>Tes frais pros, sous contrôle.</h2>
          <p style={{ color: 'var(--ink-2)', marginTop: 6, fontSize: 14, lineHeight: 1.55, maxWidth: 520 }}>
            Garde une trace de chaque dépense liée à ton activité. Ce sont autant de
            <strong> déductions fiscales</strong> au moment des impôts.
          </p>
        </div>
        <button onClick={() => setShowForm(true)} className="btn btn-primary" style={{
          padding: '14px 22px', fontSize: 15, minHeight: 52, fontWeight: 500
        }}>
          <Icon name="check" size={16} style={{ transform: 'rotate(45deg)' }} /> Ajouter une dépense
        </button>
      </div>

      {/* Sommaire bancaire */}
      <div style={{
        background: 'var(--surface)', borderRadius: 16, border: '1px solid var(--line)',
        padding: 4, display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 0
      }} className="depenses-sum">
        <div style={{ padding: '20px 24px', borderRight: '1px solid var(--line)' }}>
          <div style={{ fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Ce mois-ci</div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 28, marginTop: 6, fontVariantNumeric: 'tabular-nums' }}>{fmt(totalMonth)} <span style={{ fontSize: 16, color: 'var(--ink-3)' }}>$</span></div>
          <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 4 }}>{expenses.filter(e => e.date.startsWith(ym)).length} entrée(s)</div>
        </div>
        <div style={{ padding: '20px 24px', borderRight: '1px solid var(--line)' }}>
          <div style={{ fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Cumul {now.getFullYear()}</div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 28, marginTop: 6, fontVariantNumeric: 'tabular-nums' }}>{fmt(totalYear)} <span style={{ fontSize: 16, color: 'var(--ink-3)' }}>$</span></div>
          <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 4 }}>{expenses.length} entrée(s) au total</div>
        </div>
        <div style={{ padding: '20px 24px', background: 'var(--accent-soft)', borderRadius: 14 }}>
          <div style={{ fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--accent-2)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Revenu imposable estimé</div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 28, marginTop: 6, fontVariantNumeric: 'tabular-nums', color: 'var(--accent-2)' }}>{fmt(revenuImposable)} <span style={{ fontSize: 16 }}>$</span></div>
          <div style={{ fontSize: 12, color: 'var(--ink-2)', marginTop: 4 }}>Brut {fmt(REVENUS_BRUTS)} $ − dépenses</div>
        </div>
      </div>

      {/* Filtre période */}
      <div className="row" style={{ gap: 6, padding: 4, background: 'var(--bg-2)', borderRadius: 999, border: '1px solid var(--line)', alignSelf: 'flex-start' }}>
        {[['month', 'Ce mois'], ['year', `${now.getFullYear()}`]].map(([k, l]) => {
          const on = period === k;
          return (
            <button key={k} onClick={() => setPeriod(k)} style={{
              padding: '8px 18px', borderRadius: 999, border: 0,
              background: on ? 'var(--ink)' : 'transparent',
              color: on ? '#fff' : 'var(--ink-2)',
              fontSize: 13, fontWeight: 500, cursor: 'pointer', minHeight: 36
            }}>{l}</button>
          );
        })}
      </div>

      {/* Tableau récapitulatif */}
      <Card title={period === 'month' ? 'Dépenses du mois' : `Toutes les dépenses ${now.getFullYear()}`} action={
        <span style={{ fontSize: 13, fontFamily: 'var(--font-mono)', color: 'var(--ink-3)' }}>
          {visible.length} entrée{visible.length > 1 ? 's' : ''} · {fmt(totalVisible)} $
        </span>
      }>
        {visible.length === 0 ? (
          <div style={{ padding: '40px 16px', textAlign: 'center', color: 'var(--ink-3)', fontSize: 14 }}>
            Aucune dépense sur cette période.
            <div style={{ marginTop: 12 }}>
              <button onClick={() => setShowForm(true)} className="btn btn-ghost" style={{ fontSize: 13 }}>+ Ajouter ta première</button>
            </div>
          </div>
        ) : (
          <div style={{ display: 'grid', gap: 0 }}>
            {visible.map((e, i) => {
              const c = EXPENSE_CATEGORIES.find(x => x.id === e.cat) || { label: e.cat, emoji: '•' };
              const d = new Date(e.date).toLocaleDateString('fr-CA', { day: '2-digit', month: 'short' });
              return (
                <div key={e.id} style={{
                  display: 'grid', gridTemplateColumns: '60px 36px 1fr auto auto',
                  gap: 14, alignItems: 'center',
                  padding: '14px 0',
                  borderTop: i > 0 ? '1px solid var(--line)' : 0
                }} className="dep-row">
                  <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--ink-3)', textTransform: 'uppercase' }}>{d}</div>
                  <div style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--bg-2)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 16 }}>
                    {c.emoji}
                  </div>
                  <div>
                    <div style={{ fontSize: 14, fontWeight: 500 }}>{e.desc || c.label}</div>
                    <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 2 }}>
                      {c.label}{e.receipt && <> · <span style={{ color: 'var(--accent-2)' }}>📎 reçu joint</span></>}
                    </div>
                  </div>
                  <div style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontVariantNumeric: 'tabular-nums', textAlign: 'right' }}>
                    {fmt(e.amount)} $
                  </div>
                  <button onClick={() => remove(e.id)} aria-label="Supprimer"
                    style={{
                      width: 36, height: 36, borderRadius: 999,
                      border: 0, background: 'transparent', color: 'var(--ink-3)',
                      cursor: 'pointer', fontSize: 16, opacity: 0.5
                    }}
                    onMouseOver={ev => { ev.currentTarget.style.background = 'var(--bg-2)'; ev.currentTarget.style.opacity = 1; }}
                    onMouseOut={ev => { ev.currentTarget.style.background = 'transparent'; ev.currentTarget.style.opacity = 0.5; }}
                  >×</button>
                </div>
              );
            })}
          </div>
        )}

        {/* Récap par catégorie */}
        {Object.keys(byCat).length > 0 && (
          <div style={{ marginTop: 24, paddingTop: 18, borderTop: '1px dashed var(--line)' }}>
            <div style={{ fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 12 }}>
              Total par catégorie
            </div>
            <div style={{ display: 'grid', gap: 8 }}>
              {Object.entries(byCat).sort((a,b) => b[1]-a[1]).map(([cat, total]) => {
                const c = EXPENSE_CATEGORIES.find(x => x.id === cat) || { label: cat, emoji: '•' };
                const w = (total / totalVisible) * 100;
                return (
                  <div key={cat} style={{ display: 'grid', gridTemplateColumns: '180px 1fr 90px', gap: 12, alignItems: 'center' }} className="cat-row">
                    <div style={{ fontSize: 13 }}>{c.emoji} {c.label}</div>
                    <div style={{ height: 6, background: 'var(--bg-2)', borderRadius: 999, overflow: 'hidden' }}>
                      <div style={{ height: '100%', width: `${w}%`, background: 'var(--primary)', borderRadius: 999 }}/>
                    </div>
                    <div style={{ fontSize: 13, fontVariantNumeric: 'tabular-nums', textAlign: 'right', fontWeight: 500 }}>{fmt(total)} $</div>
                  </div>
                );
              })}
            </div>
          </div>
        )}
      </Card>

      <p style={{ fontSize: 11, color: 'var(--ink-3)', lineHeight: 1.6, fontStyle: 'italic', textAlign: 'center', marginTop: 4 }}>
        Conserve les originaux 6 ans · Les reçus joints sont stockés localement sur ton appareil.
      </p>

      <style>{`
        @media (max-width: 720px) {
          .depenses-sum { grid-template-columns: 1fr !important; }
          .depenses-sum > div { border-right: 0 !important; border-bottom: 1px solid var(--line); }
          .dep-row { grid-template-columns: 36px 1fr auto !important; }
          .dep-row > div:first-child { display: none; }
          .dep-row > button { display: none; }
          .cat-row { grid-template-columns: 1fr 90px !important; }
          .cat-row > div:nth-child(2) { display: none; }
        }
      `}</style>

      {/* Modal formulaire */}
      {showForm && (
        <div role="dialog" aria-modal="true" style={{
          position: 'fixed', inset: 0, zIndex: 1000,
          background: 'rgba(28,38,34,0.5)', backdropFilter: 'blur(6px)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          padding: 16
        }} onClick={(e) => { if (e.target === e.currentTarget) setShowForm(false); }}>
          <form onSubmit={submit} style={{
            width: '100%', maxWidth: 460, background: 'var(--bg)',
            borderRadius: 20, boxShadow: '0 40px 120px rgba(28,38,34,0.32)',
            overflow: 'hidden', maxHeight: '92vh', display: 'flex', flexDirection: 'column'
          }}>
            <div style={{ padding: '22px 24px 16px', borderBottom: '1px solid var(--line)' }}>
              <div className="row" style={{ justifyContent: 'space-between', alignItems: 'center' }}>
                <div>
                  <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--ink-3)' }}>
                    Nouvelle dépense
                  </div>
                  <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 22, marginTop: 4 }}>Ajouter un frais pro</h3>
                </div>
                <button type="button" onClick={() => setShowForm(false)} aria-label="Fermer" style={{
                  width: 36, height: 36, borderRadius: 999, border: 0,
                  background: 'var(--bg-2)', color: 'var(--ink-2)', cursor: 'pointer', fontSize: 18
                }}>×</button>
              </div>
            </div>
            <div style={{ padding: 24, overflowY: 'auto', display: 'grid', gap: 16 }}>
              {/* Date */}
              <label style={{ display: 'grid', gap: 6 }}>
                <span style={{ fontSize: 12, fontFamily: 'var(--font-mono)', color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Date</span>
                <input type="date" value={form.date} max={today}
                  onChange={(e) => setForm({ ...form, date: e.target.value })}
                  style={{
                    padding: '14px 16px', fontSize: 16, minHeight: 52,
                    border: '1px solid var(--line)', borderRadius: 12,
                    background: 'var(--surface)', color: 'var(--ink)',
                    fontFamily: 'inherit', outline: 'none'
                  }}
                />
              </label>
              {/* Catégorie */}
              <label style={{ display: 'grid', gap: 6 }}>
                <span style={{ fontSize: 12, fontFamily: 'var(--font-mono)', color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Catégorie</span>
                <select value={form.cat} onChange={(e) => setForm({ ...form, cat: e.target.value })}
                  style={{
                    padding: '14px 16px', fontSize: 16, minHeight: 52,
                    border: '1px solid var(--line)', borderRadius: 12,
                    background: 'var(--surface)', color: 'var(--ink)',
                    fontFamily: 'inherit', outline: 'none', appearance: 'none',
                    backgroundImage: 'url("data:image/svg+xml;utf8,<svg xmlns=\\"http://www.w3.org/2000/svg\\" width=\\"12\\" height=\\"12\\" viewBox=\\"0 0 12 12\\"><path d=\\"M2 4l4 4 4-4\\" stroke=\\"%236B7470\\" stroke-width=\\"1.5\\" fill=\\"none\\" stroke-linecap=\\"round\\"/></svg>")',
                    backgroundRepeat: 'no-repeat', backgroundPosition: 'right 16px center'
                  }}>
                  {EXPENSE_CATEGORIES.map(c => (
                    <option key={c.id} value={c.id}>{c.emoji}  {c.label}</option>
                  ))}
                </select>
              </label>
              {/* Montant */}
              <label style={{ display: 'grid', gap: 6 }}>
                <span style={{ fontSize: 12, fontFamily: 'var(--font-mono)', color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Montant ($)</span>
                <input type="number" inputMode="decimal" step="0.01" min="0" placeholder="0,00"
                  value={form.amount} onChange={(e) => setForm({ ...form, amount: e.target.value })}
                  required autoFocus
                  style={{
                    padding: '14px 16px', fontSize: 22, minHeight: 52,
                    border: '1px solid var(--line)', borderRadius: 12,
                    background: 'var(--surface)', color: 'var(--ink)',
                    fontFamily: 'var(--font-display)', fontVariantNumeric: 'tabular-nums',
                    outline: 'none'
                  }}
                />
              </label>
              {/* Description */}
              <label style={{ display: 'grid', gap: 6 }}>
                <span style={{ fontSize: 12, fontFamily: 'var(--font-mono)', color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Description</span>
                <input type="text" placeholder="Ex. Essence semaine du 22"
                  value={form.desc} onChange={(e) => setForm({ ...form, desc: e.target.value })}
                  style={{
                    padding: '14px 16px', fontSize: 15, minHeight: 52,
                    border: '1px solid var(--line)', borderRadius: 12,
                    background: 'var(--surface)', color: 'var(--ink)',
                    fontFamily: 'inherit', outline: 'none'
                  }}
                />
              </label>
              {/* Reçu */}
              <div style={{ display: 'grid', gap: 6 }}>
                <span style={{ fontSize: 12, fontFamily: 'var(--font-mono)', color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Reçu (optionnel)</span>
                <input ref={fileRef} type="file" accept="image/*" capture="environment"
                  onChange={(e) => handleFile(e.target.files[0])}
                  style={{ display: 'none' }}
                />
                {form.receipt ? (
                  <div className="row" style={{ gap: 12, padding: 12, background: 'var(--primary-soft)', border: '1px solid var(--primary)', borderRadius: 12 }}>
                    <img src={form.receipt.dataUrl} alt="" style={{ width: 56, height: 56, objectFit: 'cover', borderRadius: 8 }}/>
                    <div style={{ flex: 1, fontSize: 13, color: 'var(--primary)', fontWeight: 500 }}>{form.receipt.name}</div>
                    <button type="button" onClick={() => setForm({ ...form, receipt: null })}
                      style={{ background: 'transparent', border: 0, color: 'var(--ink-3)', cursor: 'pointer', fontSize: 18 }}>×</button>
                  </div>
                ) : (
                  <button type="button" onClick={() => fileRef.current?.click()}
                    style={{
                      padding: 18, minHeight: 64, fontSize: 14,
                      border: '1.5px dashed var(--line)', borderRadius: 12,
                      background: 'var(--bg-2)', color: 'var(--ink-2)',
                      cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10
                    }}>
                    📷 Télécharger le reçu (photo)
                  </button>
                )}
              </div>
            </div>
            <div style={{ padding: 16, borderTop: '1px solid var(--line)', display: 'grid', gridTemplateColumns: '1fr 2fr', gap: 10 }}>
              <button type="button" onClick={() => setShowForm(false)} className="btn btn-ghost"
                style={{ minHeight: 52, fontSize: 15 }}>Annuler</button>
              <button type="submit" className="btn btn-primary"
                style={{ minHeight: 52, fontSize: 16, fontWeight: 500 }}>Enregistrer la dépense</button>
            </div>
          </form>
        </div>
      )}
    </div>
  );
};

/* --------- Rapports financiers (intervenant autonome) --------- */
const RapportsFinanciers = ({ expenses = [] }) => {
  // Aucun historique à l'amorçage — les paiements virés apparaissent ici progressivement
  const HISTORY = [];
  const cumulatif = HISTORY.reduce((s, m) => s + m.gross, 0);
  const heuresTotal = HISTORY.reduce((s, m) => s + m.hours, 0);
  const seuil = 30000;
  const pct = Math.min(100, (cumulatif / seuil) * 100);
  const reste = Math.max(0, seuil - cumulatif);
  const totalExpenses = expenses.reduce((s, e) => s + Number(e.amount || 0), 0);
  const revenuImposable = Math.max(0, cumulatif - totalExpenses);
  const tauxMoyen = heuresTotal > 0 ? (cumulatif / heuresTotal) : 0;

  // Animation du compteur
  const [displayed, setDisplayed] = React.useState(0);
  React.useEffect(() => {
    const start = performance.now();
    const dur = 1100;
    let raf;
    const tick = (now) => {
      const t = Math.min(1, (now - start) / dur);
      const eased = 1 - Math.pow(1 - t, 3);
      setDisplayed(cumulatif * eased);
      if (t < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [cumulatif]);

  const fmt = (n) => n.toLocaleString('fr-CA', { minimumFractionDigits: 2, maximumFractionDigits: 2 });

  // Génération PDF — 2 pages : revenus + dépenses
  const generatePDF = () => {
    const w = window.open('', '_blank', 'width=900,height=1100');
    if (!w) { alert("Le bloqueur de fenêtres empêche l'ouverture du relevé. Autorise les popups pour ce site."); return; }
    const today = new Date().toLocaleDateString('fr-CA', { day: '2-digit', month: 'long', year: 'numeric' });
    const rows = HISTORY.map(m => `
      <tr>
        <td style="padding:12px 14px;border-bottom:1px solid #E6DFD3">${m.month} 2026</td>
        <td style="padding:12px 14px;border-bottom:1px solid #E6DFD3;text-align:right;font-variant-numeric:tabular-nums">${m.hours.toFixed(1)} h</td>
        <td style="padding:12px 14px;border-bottom:1px solid #E6DFD3;text-align:right;font-variant-numeric:tabular-nums;font-weight:500">${fmt(m.gross)} $</td>
      </tr>
    `).join('');

    // Dépenses : tri par date desc + groupement par catégorie
    const sorted = [...expenses].sort((a, b) => (a.date < b.date ? 1 : -1));
    const byCat = {};
    expenses.forEach(e => { byCat[e.cat] = (byCat[e.cat] || 0) + Number(e.amount || 0); });
    const catRows = Object.entries(byCat).map(([cat, total]) => {
      const c = EXPENSE_CATEGORIES.find(x => x.id === cat) || { label: cat, emoji: '•' };
      return `<tr>
        <td style="padding:10px 14px;border-bottom:1px solid #E6DFD3">${c.emoji} ${c.label}</td>
        <td style="padding:10px 14px;border-bottom:1px solid #E6DFD3;text-align:right;font-variant-numeric:tabular-nums;font-weight:500">${fmt(total)} $</td>
      </tr>`;
    }).join('');
    const expRows = sorted.map(e => {
      const c = EXPENSE_CATEGORIES.find(x => x.id === e.cat) || { label: e.cat, emoji: '•' };
      const d = new Date(e.date).toLocaleDateString('fr-CA', { day: '2-digit', month: 'short', year: 'numeric' });
      return `<tr>
        <td style="padding:10px 12px;border-bottom:1px solid #E6DFD3;font-size:12px;white-space:nowrap">${d}</td>
        <td style="padding:10px 12px;border-bottom:1px solid #E6DFD3;font-size:12px">${c.emoji} ${c.label}</td>
        <td style="padding:10px 12px;border-bottom:1px solid #E6DFD3;font-size:12px;color:#6B7470">${(e.desc || '').replace(/[<>]/g, '')}</td>
        <td style="padding:10px 12px;border-bottom:1px solid #E6DFD3;text-align:right;font-variant-numeric:tabular-nums;font-size:12px;font-weight:500">${fmt(Number(e.amount))} $</td>
      </tr>`;
    }).join('');

    w.document.write(`<!doctype html><html lang="fr"><head><meta charset="utf-8"><title>Récapitulatif annuel — Maison Sereine</title>
      <style>
        @page { margin: 18mm; }
        body { font-family: Georgia, 'Times New Roman', serif; color: #1F2420; max-width: 720px; margin: 0 auto; padding: 32px; }
        .page { page-break-after: always; }
        .page:last-of-type { page-break-after: auto; }
        .head { display:flex; justify-content:space-between; align-items:flex-end; border-bottom: 2px solid #1F2420; padding-bottom: 16px; }
        .brand { font-size: 28px; font-weight: 500; }
        .meta { font-size: 12px; color:#6B7470; text-align:right; line-height:1.5 }
        h1 { font-size: 22px; margin: 28px 0 6px; font-weight: 500; }
        .sub { color:#6B7470; font-size: 14px; margin-bottom: 24px; }
        .info { background:#F7F2EA; padding:18px 20px; border-radius:8px; font-size:13px; line-height:1.55; margin-bottom:24px; }
        table { width:100%; border-collapse: collapse; margin-top:8px; }
        th { text-align:left; padding:10px 14px; background:#F7F2EA; font-size:11px; text-transform:uppercase; letter-spacing:.08em; color:#6B7470; font-weight:500; border-bottom: 1px solid #E6DFD3; }
        th.r { text-align:right; }
        .totals { margin-top: 18px; padding: 16px 18px; background: #2C5449; color:#fff; border-radius:8px; display:flex; justify-content:space-between; align-items:baseline; }
        .totals .lab { font-size:13px; opacity:.85 }
        .totals .val { font-size:24px; font-weight:500; font-variant-numeric:tabular-nums }
        .row2 { display:grid; grid-template-columns:1fr 1fr; gap:12px; margin-top:14px }
        .stat { padding:14px 16px; background:#F7F2EA; border-radius:8px }
        .stat .l { font-size:11px; color:#6B7470; text-transform:uppercase; letter-spacing:.06em }
        .stat .v { font-size:20px; font-weight:500; margin-top:4px; font-variant-numeric:tabular-nums }
        .net { background:#FBE9D8; }
        .net .v { color:#B85A2A }
        .footer { margin-top: 36px; padding-top: 16px; border-top: 1px solid #E6DFD3; font-size: 11px; color:#6B7470; line-height:1.6 }
        .actions { margin-top: 28px; text-align:center; }
        button { background:#2C5449; color:#fff; border:0; padding:12px 22px; border-radius:8px; font-size:14px; cursor:pointer; font-family:inherit }
        @media print { .actions { display:none } }
      </style></head><body>
      <!-- PAGE 1 — Sommaire des revenus -->
      <div class="page">
        <div class="head">
          <div class="brand">Maison Sereine</div>
          <div class="meta">Récapitulatif annuel · paiements<br/>Émis le ${today}<br/>Page 1 / 2</div>
        </div>
        <h1>Sommaire des revenus 2026</h1>
        <div class="sub">Travailleur autonome · partenaire Maison Sereine</div>
        <div class="info">
          <strong>Document interne fourni par Maison Sereine.</strong> Ce document
          n'est ni un Relevé 1, ni un T4A — il récapitule les sommes brutes
          versées par Maison Sereine à des fins de référence personnelle.<br/>
          <strong>Statut&nbsp;:</strong> Travailleur autonome. Aucune retenue à la
          source n'a été effectuée. Vous êtes responsable de vos obligations
          fiscales (RRQ, RQAP, impôt, TPS/TVQ le cas échéant).
        </div>
        <table>
          <thead><tr><th>Période</th><th class="r">Heures facturées</th><th class="r">Montant brut versé</th></tr></thead>
          <tbody>${rows}</tbody>
        </table>
        <div class="totals">
          <span class="lab">Cumul brut · 1<sup>er</sup> janvier au ${today}</span>
          <span class="val">${fmt(cumulatif)} $</span>
        </div>
        <div class="row2">
          <div class="stat"><div class="l">Total heures facturées</div><div class="v">${heuresTotal.toFixed(1)} h</div></div>
          <div class="stat net"><div class="l">Revenu imposable estimé</div><div class="v">${fmt(revenuImposable)} $</div></div>
        </div>
        <div class="footer">
          Revenu imposable estimé = revenus bruts − dépenses déclarées (page 2).
          Voir détail page 2.
        </div>
      </div>

      <!-- PAGE 2 — Détail des dépenses -->
      <div class="page">
        <div class="head">
          <div class="brand">Maison Sereine</div>
          <div class="meta">Récapitulatif annuel · dépenses<br/>Émis le ${today}<br/>Page 2 / 2</div>
        </div>
        <h1>Dépenses professionnelles 2026</h1>
        <div class="sub">${expenses.length} dépense${expenses.length > 1 ? 's' : ''} déclarée${expenses.length > 1 ? 's' : ''}</div>

        <h2 style="font-size:14px;text-transform:uppercase;letter-spacing:.08em;color:#6B7470;font-weight:500;margin:18px 0 8px">Totaux par catégorie</h2>
        <table>
          <thead><tr><th>Catégorie</th><th class="r">Total</th></tr></thead>
          <tbody>${catRows || '<tr><td colspan="2" style="padding:14px;text-align:center;color:#6B7470">Aucune dépense.</td></tr>'}</tbody>
        </table>

        <h2 style="font-size:14px;text-transform:uppercase;letter-spacing:.08em;color:#6B7470;font-weight:500;margin:24px 0 8px">Liste détaillée</h2>
        <table>
          <thead><tr><th>Date</th><th>Catégorie</th><th>Description</th><th class="r">Montant</th></tr></thead>
          <tbody>${expRows || '<tr><td colspan="4" style="padding:14px;text-align:center;color:#6B7470">Aucune dépense.</td></tr>'}</tbody>
        </table>
        <div class="totals">
          <span class="lab">Total des dépenses déductibles</span>
          <span class="val">${fmt(totalExpenses)} $</span>
        </div>

        <div class="footer">
          À conserver pour vos déclarations de revenus (annexe T2125 fédérale + déclaration provinciale TP-1).
          Conservez vos reçus originaux 6 ans (Revenu Québec).
          Conformité Loi 25 — données chiffrées et limitées au strict nécessaire.<br/>
          Maison Sereine inc. · Adresse disponible sur facture · NEQ (voir documents officiels)
        </div>
      </div>

      <div class="actions">
        <button onclick="window.print()">Imprimer / Enregistrer en PDF</button>
      </div>
    </body></html>`);
    w.document.close();
  };

  return (
    <div style={{ display: 'grid', gap: 24, maxWidth: 920, margin: '0 auto' }}>
      <div>
        <div className="eyebrow" style={{ color: 'var(--accent-2)' }}>Rapports financiers</div>
        <h2 style={{ fontSize: 28, marginTop: 6 }}>Tes chiffres, en temps réel.</h2>
        <p style={{ color: 'var(--ink-2)', marginTop: 6, fontSize: 14, lineHeight: 1.55, maxWidth: 580 }}>
          Tout ce que Maison Sereine t'a versé depuis le 1<sup>er</sup> janvier — pour piloter
          tes provisions fiscales et anticiper tes obligations TPS/TVQ.
        </p>
      </div>

      {/* Cumulatif annuel — compteur héro */}
      <div style={{
        background: 'linear-gradient(135deg, var(--primary) 0%, #1F4036 100%)',
        color: '#fff', borderRadius: 20, padding: '36px 32px', position: 'relative', overflow: 'hidden'
      }}>
        <div style={{
          position: 'absolute', bottom: -60, right: -60, width: 240, height: 240,
          borderRadius: '50%', background: 'rgba(255,255,255,0.05)'
        }}/>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#F4D8B8' }}>
          Cumul brut · 1<sup>er</sup> janvier 2026 → aujourd'hui
        </div>
        <div style={{
          fontFamily: 'var(--font-display)', fontSize: 'clamp(48px, 9vw, 76px)',
          color: '#fff', marginTop: 8, lineHeight: 1, fontWeight: 500,
          fontVariantNumeric: 'tabular-nums', letterSpacing: '-0.02em'
        }}>
          {fmt(displayed)} <span style={{ fontSize: '0.5em', color: '#F4D8B8' }}>$</span>
        </div>
        <div style={{ marginTop: 14, color: '#E8DCC8', fontSize: 13 }}>
          {heuresTotal > 0
            ? <>{heuresTotal.toFixed(1)} h facturées · {HISTORY.length} mois actif{HISTORY.length > 1 ? 's' : ''} · taux moyen {tauxMoyen.toFixed(2)} $/h</>
            : <>Vos paiements virés apparaîtront ici dès votre première prestation facturée.</>
          }
        </div>
      </div>

      {/* Bloc fiscal — revenu imposable estimé */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }} className="ri-grid">
        <div style={{ padding: 18, background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 14 }}>
          <div style={{ fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Revenus bruts</div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 26, marginTop: 6, fontVariantNumeric: 'tabular-nums' }}>{fmt(cumulatif)} $</div>
        </div>
        <div style={{ padding: 18, background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 14 }}>
          <div style={{ fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Dépenses déductibles</div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 26, marginTop: 6, fontVariantNumeric: 'tabular-nums', color: 'var(--ink-2)' }}>− {fmt(totalExpenses)} $</div>
        </div>
        <div style={{ padding: 18, background: 'var(--accent-soft)', border: '2px solid var(--accent)', borderRadius: 14 }}>
          <div style={{ fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--accent-2)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Revenu imposable estimé</div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 26, marginTop: 6, fontVariantNumeric: 'tabular-nums', color: 'var(--accent-2)' }}>{fmt(revenuImposable)} $</div>
        </div>
        <style>{`@media (max-width:720px){.ri-grid{grid-template-columns:1fr !important}}`}</style>
      </div>

      {/* Alerte seuil 30 000 $ */}
      <Card title="Seuil TPS/TVQ — 30 000 $">
        <div style={{ marginBottom: 14 }}>
          <div className="row" style={{ justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8, flexWrap: 'wrap', gap: 8 }}>
            <div style={{ fontSize: 14, color: 'var(--ink-2)' }}>
              Tu es à <strong style={{ color: 'var(--ink)' }}>{pct.toFixed(1)} %</strong> du seuil.
            </div>
            <div style={{ fontSize: 13, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)' }}>
              {fmt(reste)} $ avant le seuil
            </div>
          </div>
          {/* Barre de progression */}
          <div style={{
            position: 'relative', height: 24,
            background: 'var(--bg-2)', border: '1px solid var(--line)',
            borderRadius: 999, overflow: 'hidden'
          }}>
            <div style={{
              height: '100%', width: `${pct}%`,
              background: pct < 60 ? 'var(--primary)' : pct < 85 ? 'var(--accent)' : '#B9482F',
              transition: 'width 1.1s cubic-bezier(.2,.8,.2,1)',
              borderRadius: 999,
              display: 'flex', alignItems: 'center', justifyContent: 'flex-end',
              paddingRight: 10, color: '#fff', fontSize: 11, fontFamily: 'var(--font-mono)', fontWeight: 500
            }}>
              {pct > 12 && `${fmt(cumulatif)} $`}
            </div>
            {/* Repères */}
            {[25, 50, 75].map(p => (
              <div key={p} style={{
                position: 'absolute', top: 0, bottom: 0, left: `${p}%`,
                width: 1, background: 'rgba(0,0,0,0.08)'
              }}/>
            ))}
          </div>
          <div className="row" style={{ justifyContent: 'space-between', marginTop: 6, fontSize: 10, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)' }}>
            <span>0 $</span><span>15 000 $</span><span>30 000 $</span>
          </div>
        </div>

        <div style={{
          padding: '14px 16px',
          background: pct < 85 ? 'var(--bg-2)' : 'var(--accent-soft)',
          border: '1px solid ' + (pct < 85 ? 'var(--line)' : 'var(--accent)'),
          borderRadius: 12,
          display: 'flex', gap: 12, alignItems: 'flex-start'
        }}>
          <div style={{
            width: 28, height: 28, borderRadius: 999, flexShrink: 0,
            background: pct < 85 ? 'var(--primary-soft)' : 'var(--accent-2)',
            color: pct < 85 ? 'var(--primary)' : '#fff',
            display: 'flex', alignItems: 'center', justifyContent: 'center'
          }}>
            <Icon name="sparkle" size={14} />
          </div>
          <div style={{ fontSize: 13, color: 'var(--ink), lineHeight: 1.55' }}>
            <strong>À 30 000 $</strong>, tu devras t'inscrire aux taxes (TPS/TVQ).
            <strong> Nous pouvons t'aider dans cette démarche</strong> — guide pas-à-pas
            et accompagnement avec un partenaire comptable.
          </div>
        </div>
      </Card>

      {/* Historique mensuel */}
      <Card title="Historique mensuel">
        {HISTORY.length === 0 ? (
          <EmptyState
            icon="calendar"
            title="Aucun mois d'activité enregistré"
            description="Votre historique mensuel s'affichera ici dès vos premières prestations facturées — heures, montants bruts versés et progression par rapport au seuil TPS/TVQ."
          />
        ) : (
          <div style={{ display: 'grid', gap: 0 }}>
            {HISTORY.map((m, i) => {
              const max = Math.max(...HISTORY.map(x => x.gross));
              const w = (m.gross / max) * 100;
              return (
                <div key={m.month} style={{
                  display: 'grid', gridTemplateColumns: '110px 1fr 110px 90px',
                  gap: 14, alignItems: 'center',
                  padding: '14px 0',
                  borderTop: i > 0 ? '1px solid var(--line)' : 0
                }} className="hist-row">
                  <div style={{ fontSize: 14, fontWeight: 500 }}>{m.month}</div>
                  <div style={{ height: 8, background: 'var(--bg-2)', borderRadius: 999, position: 'relative', overflow: 'hidden' }}>
                    <div style={{ position: 'absolute', inset: 0, width: `${w}%`, background: 'var(--primary)', borderRadius: 999 }}/>
                  </div>
                  <div style={{ fontSize: 13, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)', textAlign: 'right' }}>{m.hours.toFixed(1)} h</div>
                  <div style={{ fontFamily: 'var(--font-display)', fontSize: 16, textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{fmt(m.gross)} $</div>
                </div>
              );
            })}
          </div>
        )}
      </Card>

      {/* Action principale — Récapitulatif annuel, centré sous l'Historique mensuel */}
      <div style={{
        display: 'flex',
        justifyContent: 'center',
        marginTop: 32,
      }}>
        <button
          onClick={generatePDF}
          className="btn btn-primary"
          style={{
            width: '100%',
            maxWidth: 460,
            padding: '20px 24px',
            fontSize: 15,
            justifyContent: 'flex-start',
            textAlign: 'left',
            minHeight: 84,
            alignItems: 'center',
            gap: 16,
          }}
        >
          <div style={{
            width: 44, height: 44, borderRadius: 12, flexShrink: 0,
            background: 'rgba(255,255,255,0.16)',
            display: 'flex', alignItems: 'center', justifyContent: 'center'
          }}>
            <Icon name="download" size={20} />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 500 }}>
              Générer mon récapitulatif annuel
            </div>
            <div style={{ fontSize: 12, opacity: 0.85, marginTop: 4 }}>
              PDF cumulatif · missions, dates et montants bruts
            </div>
          </div>
        </button>
      </div>

      <p style={{
        fontSize: 11, color: 'var(--ink-3)', lineHeight: 1.6,
        fontStyle: 'italic', textAlign: 'center', marginTop: 4
      }}>
        Maison Sereine fournit le relevé brut. Les déductions, cotisations RRQ/RQAP et déclarations
        TP-1 / T2125 restent ta responsabilité — on te met les outils à portée de main.
      </p>

      <style>{`
        @media (max-width: 720px) {
          .hist-row { grid-template-columns: 90px 1fr 90px !important; }
          .hist-row > div:nth-child(3) { display: none; }
        }
      `}</style>
    </div>
  );
};

/* --------- Statut de Partenaire — éducation autonome --------- */
const StatutPartenaire = () => {
  // Comparateur — données illustratives
  const PUBLIC = { net: 19.80, label: "Salarié — secteur public" };
  const MAISON_SEREINE = { net: 26.90, label: "Partenaire Maison Sereine" };
  const ecart = MAISON_SEREINE.net - PUBLIC.net;

  return (
    <div style={{ display: 'grid', gap: 24, maxWidth: 920, margin: '0 auto' }}>
      {/* Hero — Statut de Partenaire (englobe désormais les paramètres profil) */}
      <div style={{
        background: 'linear-gradient(135deg, var(--primary) 0%, var(--primary-2, #1F4036) 100%)',
        color: '#fff', borderRadius: 20, padding: 36,
        position: 'relative', overflow: 'hidden'
      }}>
        <div style={{
          position: 'absolute', top: -40, right: -40,
          width: 200, height: 200, borderRadius: '50%',
          background: 'rgba(255,255,255,0.06)'
        }}/>
        <div className="row" style={{ gap: 10, marginBottom: 12 }}>
          <Icon name="sparkle" size={16} style={{ color: '#F4D8B8' }} />
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#F4D8B8' }}>
            Statut de Partenaire
          </span>
        </div>
        <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 30, lineHeight: 1.2, color: '#fff', maxWidth: 540, marginTop: 0 }}>
          Tu n'es pas un salarié. Tu es un <em>partenaire</em>.
        </h2>
        <p style={{ marginTop: 14, color: '#E8DCC8', fontSize: 15, lineHeight: 1.6, maxWidth: 540 }}>
          Ça veut dire plus de liberté&nbsp;: ton horaire, tes missions, ton tarif net.
          Et quelques responsabilités qu'on t'aide à gérer simplement, sans paperasse inutile.
        </p>

        {/* Paramètres du profil — intégrés comme sous-sections logiques du Statut de Partenaire */}
        <div style={{
          marginTop: 28, paddingTop: 22,
          borderTop: '1px solid rgba(255,255,255,0.18)'
        }}>
          <div style={{
            fontFamily: 'var(--font-mono)', fontSize: 11,
            letterSpacing: '0.1em', textTransform: 'uppercase',
            color: '#F4D8B8', marginBottom: 14
          }}>
            Paramètres du profil
          </div>
          <div style={{ display: 'grid', gap: 14 }}>
            {[
              {
                t: "Liberté de plateforme",
                d: "Vous êtes libre de proposer vos services sur d'autres plateformes en tout temps.",
                chip: "Sans exclusivité",
              },
              {
                t: "Refus de mission",
                d: "Vous pouvez refuser n'importe quelle mission, sans justification ni pénalité.",
                chip: "Libre choix",
              },
            ].map((p) => (
              <div
                key={p.t}
                className="row"
                style={{
                  justifyContent: 'space-between',
                  alignItems: 'flex-start',
                  gap: 14, padding: '10px 0',
                  borderBottom: '1px solid rgba(255,255,255,0.10)'
                }}
              >
                <div>
                  <div style={{ fontSize: 14, fontWeight: 500, color: '#fff' }}>{p.t}</div>
                  <div style={{ fontSize: 13, color: '#D7CFC2', marginTop: 4, lineHeight: 1.5 }}>
                    {p.d}
                  </div>
                </div>
                <span
                  className="row"
                  style={{
                    gap: 6, padding: '4px 10px', borderRadius: 999,
                    background: 'rgba(255,255,255,0.14)', color: '#fff',
                    border: '1px solid rgba(244,216,184,0.4)',
                    whiteSpace: 'nowrap', fontSize: 12, fontWeight: 500,
                    alignSelf: 'flex-start'
                  }}
                >
                  <Icon name="check" size={12} /> {p.chip}
                </span>
              </div>
            ))}
            <div
              className="row"
              style={{
                justifyContent: 'space-between',
                alignItems: 'flex-start',
                gap: 14, padding: '10px 0'
              }}
            >
              <div>
                <div style={{ fontSize: 14, fontWeight: 500, color: '#fff' }}>Récapitulatif annuel</div>
                <div style={{ fontSize: 13, color: '#D7CFC2', marginTop: 4, lineHeight: 1.5 }}>
                  Maison Sereine prépare un récapitulatif annuel des montants bruts versés.
                  <em style={{ color: '#C9C1B3' }}> Document interne — n'est ni un Relevé 1, ni un T4A.</em>
                </div>
              </div>
              <button
                type="button"
                className="row"
                style={{
                  gap: 6, padding: '8px 14px', minHeight: 36,
                  borderRadius: 999, fontSize: 13, fontWeight: 500,
                  background: '#fff', color: 'var(--primary)',
                  border: 'none', whiteSpace: 'nowrap', cursor: 'pointer',
                  alignSelf: 'flex-start'
                }}
              >
                <Icon name="download" size={13} /> Télécharger
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* Comparateur de revenus — version épurée centrée */}
      <Card title="Combien tu reçois vraiment, par heure">
        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))',
          gap: 24,
          alignItems: 'stretch',
          marginTop: 8,
        }}>
          {/* Salarié */}
          <div style={{
            padding: '32px 24px',
            background: 'var(--bg-2)',
            border: '1px solid var(--line)',
            borderRadius: 14,
            textAlign: 'center',
            display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
          }}>
            <div>
              <div style={{
                fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.1em',
                textTransform: 'uppercase', color: 'var(--ink-3)'
              }}>
                {PUBLIC.label}
              </div>
              <div style={{
                fontFamily: 'var(--font-display)', fontSize: 44, lineHeight: 1.05,
                color: 'var(--ink)', marginTop: 16
              }}>
                {PUBLIC.net.toFixed(2)} $
                <span style={{ fontSize: 16, fontFamily: 'var(--font-body)', color: 'var(--ink-3)' }}> / h</span>
              </div>
            </div>
            <div style={{ fontSize: 13, color: 'var(--ink-3)', marginTop: 18, lineHeight: 1.5 }}>
              Net reçu après déductions à la source.
            </div>
          </div>

          {/* Partenaire Maison Sereine */}
          <div style={{
            padding: '32px 24px',
            background: 'var(--accent-soft)',
            border: '2px solid var(--accent)',
            borderRadius: 14,
            textAlign: 'center',
            display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
            position: 'relative',
          }}>
            <div>
              <div style={{
                fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.1em',
                textTransform: 'uppercase', color: 'var(--accent-2)'
              }}>
                {MAISON_SEREINE.label}
              </div>
              <div style={{
                fontFamily: 'var(--font-display)', fontSize: 56, lineHeight: 1.05,
                color: 'var(--accent-2)', marginTop: 16
              }}>
                {MAISON_SEREINE.net.toFixed(2)} $
                <span style={{ fontSize: 18, fontFamily: 'var(--font-body)', color: 'var(--accent-2)' }}> / h</span>
              </div>
            </div>
            <div style={{ fontSize: 13, color: 'var(--ink-2)', marginTop: 18, lineHeight: 1.5 }}>
              Montant exact versé. À provisionner pour les obligations fiscales (~25–30 %).
            </div>
          </div>
        </div>

        {/* Synthèse écart */}
        <div style={{
          marginTop: 28, textAlign: 'center',
          fontSize: 14, color: 'var(--ink-2)', lineHeight: 1.6
        }}>
          Soit&nbsp;
          <strong style={{ color: 'var(--accent-2)' }}>+{ecart.toFixed(2)} $/h</strong>
          &nbsp;de plus pour chaque heure travaillée.
        </div>
      </Card>

      {/* Boîte à outils fiscale */}
      <Card title="🛠️ Boîte à outils fiscale">
        <p style={{ color: 'var(--ink-2)', fontSize: 14, lineHeight: 1.6, marginBottom: 18 }}>
          Quelques liens utiles, choisis pour aller à l'essentiel.
          Tout est gratuit et officiel — sources Revenu Québec et ARC.
        </p>
        <div style={{ display: 'grid', gap: 10 }}>
          {[
            {
              title: "Travailleurs autonomes — Revenu Québec",
              desc: "Le guide officiel : déclarations, acomptes provisionnels, dépenses admissibles.",
              url: "https://www.revenuquebec.ca/fr/citoyens/travailleurs-autonomes/",
              tag: "Guide officiel"
            },
            {
              title: "TPS / TVQ — quand s'inscrire",
              desc: "Tu n'as pas besoin de t'inscrire avant 30 000 $ de CA brut sur 4 trimestres.",
              url: "https://www.revenuquebec.ca/fr/entreprises/taxes/tpstvh-et-tvq/inscription-aux-fichiers-de-la-tps-et-de-la-tvq/",
              tag: "Seuil 30 000 $"
            },
            {
              title: "Acomptes provisionnels — comment estimer",
              desc: "Calculatrice officielle pour répartir tes paiements sur l'année.",
              url: "https://www.revenuquebec.ca/fr/citoyens/declaration-de-revenus/payer-ou-etre-rembourse/acomptes-provisionnels/",
              tag: "Calculatrice"
            },
            {
              title: "ARC — Agence du revenu du Canada (Fédéral)",
              desc: "Portail fédéral : déclarations, formulaires, paiements et obligations.",
              url: "https://www.canada.ca/fr/agence-revenu.html",
              tag: "Fédéral"
            },
          ].map((r, i) => (
            <a
              key={i}
              href={r.url}
              target="_blank"
              rel="noopener noreferrer"
              aria-label={`${r.title} (ouvre dans un nouvel onglet)`}
              style={{
                display: 'grid', gridTemplateColumns: '1fr auto', gap: 16,
                padding: '14px 16px',
                background: 'var(--surface)', border: '1px solid var(--line)',
                borderRadius: 12, textDecoration: 'none', color: 'inherit',
                cursor: 'pointer',
                transition: 'border-color .15s ease, transform .15s ease, box-shadow .15s ease'
              }}
              onMouseOver={e => {
                e.currentTarget.style.borderColor = 'var(--primary)';
                e.currentTarget.style.transform = 'translateY(-1px)';
                e.currentTarget.style.boxShadow = '0 4px 12px rgba(27, 42, 34, 0.06)';
              }}
              onMouseOut={e => {
                e.currentTarget.style.borderColor = 'var(--line)';
                e.currentTarget.style.transform = 'translateY(0)';
                e.currentTarget.style.boxShadow = 'none';
              }}
            >
              <div>
                <div className="row" style={{ gap: 8, alignItems: 'baseline', flexWrap: 'wrap' }}>
                  <div style={{ fontFamily: 'var(--font-display)', fontSize: 16 }}>{r.title}</div>
                  <span style={{
                    fontSize: 10, padding: '3px 8px', borderRadius: 999,
                    background: 'var(--primary-soft)', color: 'var(--primary)',
                    fontFamily: 'var(--font-mono)', letterSpacing: '0.04em'
                  }}>{r.tag}</span>
                </div>
                <div style={{ fontSize: 13, color: 'var(--ink-2)', marginTop: 4, lineHeight: 1.5 }}>{r.desc}</div>
              </div>
              <Icon name="arrow-right" size={16} style={{ color: 'var(--ink-3)', alignSelf: 'center' }} />
            </a>
          ))}
        </div>

        <div style={{
          marginTop: 18, padding: '12px 14px',
          background: 'var(--primary-soft)', borderRadius: 10,
          display: 'flex', gap: 10, alignItems: 'flex-start'
        }}>
          <Icon name="sparkle" size={14} style={{ color: 'var(--primary)', marginTop: 3, flexShrink: 0 }} />
          <div style={{ fontSize: 12.5, color: 'var(--ink-2), lineHeight: 1.55' }}>
            <strong style={{ color: 'var(--ink)' }}>Bon réflexe&nbsp;:</strong> mets de côté
            ~25 % de chaque virement Maison Sereine dans un compte épargne séparé.
            Tu seras prêt·e pour les acomptes provisionnels sans stress.
          </div>
        </div>
      </Card>

      {/* Mindset card */}
      <div style={{
        background: 'var(--surface)', border: '1px solid var(--line)',
        borderRadius: 16, padding: 28, textAlign: 'center'
      }}>
        <div style={{ fontSize: 32, marginBottom: 8 }}>🌱</div>
        <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 22, marginTop: 0 }}>
          Tu construis quelque chose
        </h3>
        <p style={{ color: 'var(--ink-2)', fontSize: 14, lineHeight: 1.6, maxWidth: 460, margin: '10px auto 0' }}>
          Chaque mission est une expérience qui compte sur ton CV.
          Chaque dollar que tu provisionnes, c'est de l'autonomie en plus.
          On est là pour t'outiller — pas pour décider à ta place.
        </p>
      </div>
    </div>
  );
};

/* --------- Modal d'onboarding — validation de compréhension --------- */
const OnboardingModal = ({ onDismiss }) => {
  const [step, setStep] = React.useState(1); // 1=intro, 2=validation
  const [agreed, setAgreed] = React.useState(false);

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape' && step === 2 && agreed) onDismiss(); };
    window.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = prev;
    };
  }, [step, agreed, onDismiss]);

  return (
    <div role="dialog" aria-modal="true" style={{
      position: 'fixed', inset: 0, zIndex: 1000,
      background: 'rgba(28,38,34,0.5)', backdropFilter: 'blur(6px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 24
    }}>
      <style>{`
        @keyframes maisRise { from { opacity: 0; transform: translateY(12px) } to { opacity: 1; transform: translateY(0) } }
      `}</style>
      <div style={{
        width: '100%', maxWidth: 560,
        background: 'var(--bg)', borderRadius: 20,
        boxShadow: '0 40px 120px rgba(28,38,34,0.32)',
        animation: 'maisRise .3s ease-out',
        overflow: 'hidden', maxHeight: '90vh', display: 'flex', flexDirection: 'column'
      }}>
        <div style={{
          padding: '28px 32px 20px',
          background: 'linear-gradient(135deg, var(--primary) 0%, #1F4036 100%)',
          color: '#fff'
        }}>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#F4D8B8' }}>
            Bienvenue chez Maison Sereine
          </div>
          <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 24, marginTop: 8, color: '#fff', lineHeight: 1.2 }}>
            {step === 1 ? "Avant de commencer — 2 minutes" : "Une dernière chose"}
          </h3>
        </div>

        <div style={{ padding: '24px 32px', overflowY: 'auto' }}>
          {step === 1 ? (
            <>
              <p style={{ color: 'var(--ink-2)', fontSize: 15, lineHeight: 1.6, marginTop: 0 }}>
                Tu rejoins Maison Sereine en tant que <strong>partenaire indépendant·e</strong> —
                c'est un statut qui te donne beaucoup de liberté.
              </p>
              <ul style={{ listStyle: 'none', padding: 0, margin: '20px 0 0', display: 'grid', gap: 12 }}>
                {[
                  { t: "Tu choisis tes disponibilités", d: "Aucun horaire imposé." },
                  { t: "Tu reçois ton tarif brut direct", d: "Aucune retenue à la source — c'est à toi de gérer tes cotisations." },
                  { t: "Tu gères tes obligations fiscales", d: "On te fournit un récapitulatif annuel + des outils." },
                  { t: "Tu peux travailler ailleurs", d: "Aucune exclusivité, ni avant ni pendant." },
                ].map(x => (
                  <li key={x.t} style={{ display: 'grid', gridTemplateColumns: '32px 1fr', gap: 12 }}>
                    <div style={{
                      width: 32, height: 32, borderRadius: 999,
                      background: 'var(--primary-soft)', color: 'var(--primary)',
                      display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0
                    }}>
                      <Icon name="check" size={14} />
                    </div>
                    <div>
                      <div style={{ fontSize: 14, fontWeight: 500 }}>{x.t}</div>
                      <div style={{ fontSize: 13, color: 'var(--ink-3)', marginTop: 2 }}>{x.d}</div>
                    </div>
                  </li>
                ))}
              </ul>
            </>
          ) : (
            <>
              <p style={{ color: 'var(--ink-2)', fontSize: 15, lineHeight: 1.6, marginTop: 0 }}>
                Pour démarrer en toute clarté, on te demande de <strong>confirmer</strong>
                que tu as bien compris ton statut. Tu peux revenir consulter
                « Statut de Partenaire » à tout moment.
              </p>

              <label style={{
                display: 'grid', gridTemplateColumns: '24px 1fr', gap: 14,
                padding: '18px 20px', marginTop: 20,
                background: agreed ? 'var(--primary-soft)' : 'var(--surface)',
                border: '2px solid ' + (agreed ? 'var(--primary)' : 'var(--line)'),
                borderRadius: 14, cursor: 'pointer',
                transition: 'all .15s ease'
              }}>
                <input type="checkbox" checked={agreed} onChange={e => setAgreed(e.target.checked)}
                  style={{
                    width: 22, height: 22, marginTop: 2, accentColor: 'var(--primary)', cursor: 'pointer'
                  }}
                />
                <div style={{ fontSize: 14, color: 'var(--ink), lineHeight: 1.55' }}>
                  J'ai compris que je suis <strong>responsable de mes obligations
                  fiscales et sociales</strong> en tant qu'indépendant·e.
                </div>
              </label>

              <p style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 14, lineHeight: 1.5, fontStyle: 'italic' }}>
                Maison Sereine fournit un récapitulatif annuel des montants bruts versés.
                Les cotisations RRQ, RQAP, impôt et TPS/TVQ (le cas échéant) restent
                de ta responsabilité — on est là pour t'outiller.
              </p>
            </>
          )}
        </div>

        <div className="row" style={{
          padding: '16px 32px 24px', gap: 12, justifyContent: 'flex-end',
          borderTop: '1px solid var(--line)', flexWrap: 'wrap'
        }}>
          {step === 1 ? (
            <button className="btn btn-primary" onClick={() => setStep(2)}
              style={{ padding: '12px 22px', fontSize: 15 }}>
              Continuer <Icon name="arrow-right" size={15} />
            </button>
          ) : (
            <button className="btn btn-primary" onClick={onDismiss} disabled={!agreed}
              style={{
                padding: '12px 22px', fontSize: 15,
                opacity: agreed ? 1 : 0.5, cursor: agreed ? 'pointer' : 'not-allowed'
              }}>
              C'est noté, je démarre <Icon name="arrow-right" size={15} />
            </button>
          )}
        </div>
      </div>
    </div>
  );
};

window.DashboardPage = DashboardPage;
