// screen-home.jsx — Accueil Sauv'Moi · mobile + desktop

// ── Images réelles (Unsplash/Pexels, licence libre, aucune attribution
//    requise) partagées entre les 7 conseils du jour ET les 10 modules de
//    formation (voir data/training-modules.js) — associées par thème plutôt
//    qu'une image par entrée, pour rester dans le lot fourni. ────────────
const IMG_PLS = 'https://images.unsplash.com/photo-1649260257572-91bf6f94cff6?fm=jpg&q=80&w=600&auto=format&fit=crop';
const IMG_RCP = 'https://images.unsplash.com/photo-1755548376576-e045f6e01773?fm=jpg&q=80&w=600&auto=format&fit=crop';
const IMG_URGENCE = 'https://images.unsplash.com/photo-1734174040265-ef440f9373dc?fm=jpg&q=80&w=600&auto=format&fit=crop';
const IMG_TROUSSE_ROUGE = 'https://images.unsplash.com/photo-1624638760852-8ede1666ab07?fm=jpg&q=80&w=600&auto=format&fit=crop';
const IMG_TROUSSE_VERTE = 'https://images.unsplash.com/photo-1564144573017-8dc932e0039e?fm=jpg&q=80&w=600&auto=format&fit=crop';
const IMG_STETHOSCOPE = 'https://images.pexels.com/photos/20100296/pexels-photo-20100296.jpeg?auto=compress&cs=tinysrgb&w=600';

// ── Conseils PSC1 — rotation sur les 7 jours de la semaine ───────────────
const DAILY_TIPS = [
  { icon: 'user-round', image: IMG_PLS,
    fr: { title: 'Position Latérale de Sécurité', text: 'Pour une personne inconsciente qui respire, placez-la en PLS pour dégager les voies aériennes et éviter l\'étouffement.' },
    en: { title: 'Recovery Position', text: 'For an unconscious person who is breathing, place them in the recovery position to keep the airway clear and prevent choking.' } },
  { icon: 'wind', image: IMG_URGENCE,
    fr: { title: 'Étouffement — Manœuvre de Heimlich', text: '5 tapes dans le dos puis 5 compressions abdominales. Répétez jusqu\'à dégagement complet de l\'obstruction.' },
    en: { title: 'Choking — Heimlich Maneuver', text: '5 back blows followed by 5 abdominal thrusts. Repeat until the obstruction is fully cleared.' } },
  { icon: 'heart-pulse', image: IMG_RCP,
    fr: { title: 'Massage cardiaque', text: '30 compressions (5–6 cm, 100–120/min) alternées avec 2 insufflations. Continuez jusqu\'à l\'arrivée des secours.' },
    en: { title: 'Chest Compressions (CPR)', text: '30 compressions (5–6 cm deep, 100–120/min) alternated with 2 rescue breaths. Continue until help arrives.' } },
  { icon: 'flame', image: IMG_TROUSSE_VERTE,
    fr: { title: 'Brûlure — réflexe immédiat', text: '15 minutes sous eau tempérée courante. Jamais de glace, de beurre ou de dentifrice sur la brûlure.' },
    en: { title: 'Burns — Immediate Response', text: '15 minutes under cool running water. Never apply ice, butter, or toothpaste to a burn.' } },
  { icon: 'droplets', image: IMG_TROUSSE_ROUGE,
    fr: { title: 'Hémorragie — compression directe', text: 'Appuyez fermement avec un linge propre sur la plaie sans relâcher. Appelez le 185 immédiatement.' },
    en: { title: 'Bleeding — Direct Pressure', text: 'Press firmly on the wound with a clean cloth without releasing. Call 185 immediately.' } },
  { icon: 'brain', image: IMG_STETHOSCOPE,
    fr: { title: 'Reconnaître un AVC (FAST)', text: 'Visage asymétrique · Bras tombant · Parole difficile → Temps = urgence absolue. Appelez le 185.' },
    en: { title: 'Recognizing a Stroke (FAST)', text: 'Face drooping · Arm weakness · Speech difficulty → Time is critical. Call 185.' } },
  { icon: 'thermometer', image: IMG_URGENCE,
    fr: { title: 'Malaise — premiers gestes', text: 'Allongez la victime, surélevez les jambes, desserrez les vêtements. Si inconsciente → mettez en PLS.' },
    en: { title: 'Feeling Faint — First Steps', text: 'Lay the person down, raise their legs, loosen tight clothing. If unconscious → place in the recovery position.' } },
];

// ── Barre de navigation fond bleu foncé avec SOS pulsé ────────────────────
function HomeTabBar({ active, nav }) {
  const t = useTranslation();
  const TABS = [
    { id: 'home',     icon: 'home',      label: t('tabbar.home') },
    { id: 'training', icon: 'book-open', label: t('tabbar.training') },
    { id: 'sos',      icon: 'siren',     label: t('tabbar.sos'), special: true },
    { id: 'map',      icon: 'map-pin',   label: t('tabbar.map') },
    { id: 'profile',  icon: 'user',      label: t('tabbar.profile') },
  ];

  return (
    <div style={{
      // Fond bleu marine uni (--sm-navy-deep, jamais réécrit sous .sm-dark —
      // même exemption que le voile de la carte "Que se passe-t-il ?" et
      // l'écran de démarrage : chrome intentionnellement sombre dans les
      // deux thèmes) plutôt que le dégradé bleu vif précédent.
      background: 'var(--sm-navy-deep)',
      borderTop: '1px solid rgba(255,255,255,0.08)',
      display: 'flex',
      alignItems: 'flex-start',
      padding: '10px 0 28px',
      flexShrink: 0,
      overflow: 'visible',
      position: 'relative',
    }}>
      {TABS.map(tab => {

        // ── Bouton SOS central surélevé (réduit pour rester proportionné
        //    face aux autres onglets, tout en restant reconnaissable) ──
        if (tab.special) return (
          <div key="sos" style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 5, marginTop: -26 }}>
            <button
              onClick={() => nav.go('sos')}
              style={{ position: 'relative', width: 54, height: 54, background: 'none', border: 'none', cursor: 'pointer', padding: 0 }}
              aria-label={t('tabbar.sos_aria')}
            >
              <div className="sm-halo" style={{ borderColor: 'rgba(229,57,53,0.5)' }} />
              <div className="sm-halo delay1" style={{ borderColor: 'rgba(229,57,53,0.3)' }} />
              <div style={{
                position: 'absolute', inset: 0, borderRadius: '50%',
                background: 'var(--sm-red)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                boxShadow: '0 4px 16px rgba(229,57,53,0.45)',
              }}>
                <Icon name="siren" size={22} color="white" strokeWidth={2} />
              </div>
            </button>
            <span style={{ fontSize: 10.5, color: 'white', fontWeight: 700, fontFamily: 'var(--font-ui)' }}>{t('tabbar.sos')}</span>
          </div>
        );

        // ── Onglets normaux — icône/label blancs, trait vert discret sous
        //    l'icône pour l'onglet actif (remplace l'ancienne bordure
        //    blanche en haut). La barre garde sa place (transparente quand
        //    inactive) pour ne jamais faire varier la hauteur de la tabbar. ──
        const isActive = active === tab.id;
        const iconColor = tab.disabled
          ? 'rgba(255,255,255,0.25)'
          : isActive ? 'white' : 'rgba(255,255,255,0.55)';

        const GO = { home: () => nav.reset('home'), training: () => nav.go('training'), map: () => nav.go('map'), profile: () => nav.go('profile') };
        return (
          <button
            key={tab.id}
            onClick={() => !tab.disabled && GO[tab.id]?.()}
            style={{
              flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
              paddingTop: 8, paddingBottom: 0, paddingLeft: '4px', paddingRight: '4px',
              background: 'none', border: 'none',
              cursor: tab.disabled ? 'default' : 'pointer',
              fontFamily: 'var(--font-ui)',
            }}
          >
            <Icon name={tab.icon} size={22} color={iconColor} />
            <span style={{
              width: 14, height: 3, borderRadius: 2, margin: '3px 0 1px',
              background: isActive && !tab.disabled ? 'var(--sm-green)' : 'transparent',
            }} />
            <span style={{ fontSize: 10.5, color: iconColor, fontWeight: isActive ? 600 : 400 }}>
              {tab.label}
            </span>
          </button>
        );
      })}
    </div>
  );
}

// ── Carte "Conseil du jour" — dégradé vert doux + image illustrative ──────
// Composant local (pas le Banner partagé — Banner sert aussi de toast profil
// et de bandeau GPS/erreurs, un style dédié ici évite de dévier ces usages).
// Couleurs de texte calquées sur BANNER_VARIANTS(_DARK).success dans
// frames.jsx pour rester cohérentes avec le reste de l'app (contrastes déjà
// vérifiés WCAG côté Banner). Image spécifique par conseil (tip.image, voir
// DAILY_TIPS) plutôt qu'une image par défaut unique.
function TipOfDayCard({ tip }) {
  const theme = useTheme();
  const isDark = theme === 'dark';
  return (
    <div style={{
      position: 'relative', overflow: 'hidden', display: 'flex', gap: 14, alignItems: 'center',
      borderRadius: 'var(--sm-radius)', padding: '16px 16px 16px 20px',
      background: isDark
        ? 'linear-gradient(120deg, #16281E 0%, var(--sm-paper-2) 75%)'
        : 'linear-gradient(120deg, #EAF6EE 0%, #FFFFFF 75%)',
    }}>
      <div style={{ position: 'absolute', top: 0, bottom: 0, left: 0, width: 4, background: 'var(--sm-green)' }} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 15, fontWeight: 700, color: isDark ? '#8FDB7A' : '#145A32', marginBottom: 4, fontFamily: 'var(--font-ui)' }}>
          {tip.title}
        </div>
        <div style={{ fontSize: 13, color: 'var(--sm-ink-500)', lineHeight: 1.5 }}>
          {tip.text}
        </div>
      </div>
      <FallbackImage
        src={tip.image}
        fallbackColor="var(--sm-soft-green)"
        style={{ width: 74, height: 74, borderRadius: 12, flexShrink: 0 }}
      />
    </div>
  );
}

// ── Carte "Reprise de formation" — même structure que la carte Scanner QR
// (sm-icon-tile + texte + sm-icon-circle), pas un nouveau style local. Charge
// les modules déjà exposés par l'API formation (screen-training.jsx utilise
// la même route) plutôt que de dupliquer une source de progression. Rendu en
// 3 temps, sans jamais retomber à une hauteur nulle entre chaque (pas de
// nouveau "vide" pendant le chargement) :
//   - chargement  : même carte, sous-titre "Chargement…"
//   - échec réseau: rien affiché (mieux qu'une carte cassée ou une donnée
//     de progression potentiellement fausse)
//   - chargé      : progression + module suivant si un module est
//     déverrouillé, message de parcours terminé sinon.
function TrainingResumeCard({ nav, t, lang }) {
  const [modules, setModules] = useState(null);
  const [failed, setFailed] = useState(false);

  useEffect(() => {
    window.API.trainingModules(lang).then(setModules).catch(() => setFailed(true));
  }, [lang]);

  if (failed) return null;

  const completed = modules ? modules.filter(m => m.status === 'completed').length : 0;
  const total = modules ? modules.length : 10;
  const next = modules ? modules.find(m => m.status === 'unlocked') : null;

  const subtitle = !modules
    ? t('home.training_loading')
    : next
      ? t('home.training_progress').replace('{done}', completed).replace('{total}', total).replace('{module}', next.title)
      : t('home.training_all_done').replace('{total}', total);

  return (
    <button
      onClick={() => {
        if (!modules) return;
        if (next) { window.SM.trainingModule = next; nav.go('training_module'); }
        else nav.go('training');
      }}
      style={{
        display: 'flex', width: '100%', alignItems: 'center', gap: 14, flexShrink: 0,
        padding: '15px 16px', borderRadius: 'var(--sm-radius)',
        background: 'white',
        cursor: modules ? 'pointer' : 'default', textAlign: 'left',
        boxShadow: '0 2px 8px rgba(10,22,40,0.06)',
      }}
    >
      <div className="sm-icon-tile" style={{ background: 'var(--sm-soft-green)' }}>
        <Icon name="graduation-cap" size={22} color="var(--sm-green)" strokeWidth={1.9} />
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="sm-serif" style={{ fontSize: 16, color: 'var(--sm-ink)', marginBottom: 3 }}>
          {t('home.training_resume_title')}
        </div>
        <div style={{ fontSize: 13, color: 'var(--sm-ink-500)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {subtitle}
        </div>
      </div>
      <div className="sm-icon-circle" style={{ background: 'var(--sm-soft-green)' }}>
        <Icon name="arrow-right" size={16} color="var(--sm-green)" strokeWidth={2} />
      </div>
    </button>
  );
}

// ════════════════════════════════════════════════════════════════════════════
// ACCUEIL MOBILE
// ════════════════════════════════════════════════════════════════════════════
function HomeMobile({ nav, lang }) {
  useLucide();
  const t = useTranslation();
  const currentLang = useLang();
  window.useSM(); // re-render quand SM.user change (après connexion)

  // Salutation dynamique
  const hour     = new Date().getHours();
  const user     = window.SM?.user;
  const prenom   = (user?.prenom || user?.name?.split(' ')[0] || '').trim() || t('home.default_name');
  const initials = user?.initials || prenom.slice(0, 2).toUpperCase();
  const _AV_COLORS = ['#E53935', '#4A90C2', '#2E6B4F', '#C77A2B', '#6B4F8C'];
  const avatarBg = _AV_COLORS[(initials.charCodeAt(0) || 0) % _AV_COLORS.length];

  // Conseil du jour (indexé sur le jour de la semaine)
  const tipEntry = DAILY_TIPS[new Date().getDay()];
  const tip = { icon: tipEntry.icon, image: tipEntry.image, ...(currentLang === 'en' ? tipEntry.en : tipEntry.fr) };

  // Notifications in-app
  const [notifs, setNotifs] = useState([]);
  const [showNotifs, setShowNotifs] = useState(false);
  const unreadCount = notifs.filter(n => !n.read).length;

  useEffect(() => {
    window.API.notifications().then(setNotifs).catch(() => {});
  }, []);

  const openNotif = () => {
    setShowNotifs(true);
    // Marquer toutes comme lues
    notifs.filter(n => !n.read).forEach(n => {
      window.API.markNotifRead(n.id).catch(() => {});
    });
    setNotifs(prev => prev.map(n => ({ ...n, read: true })));
  };

  return (
    <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      {/* ── En-tête dégradé ─────────────────────────────────────────── */}
      <div style={{
        background: 'linear-gradient(180deg, #f8f9fa, white)',
        padding: '16px 20px 14px',
        display: 'flex', alignItems: 'center', gap: 12,
        borderBottom: '1px solid var(--sm-line)',
        flexShrink: 0,
      }}>
        {/* Logo Sauv'Moi — cliquable → notifications */}
        <button
          onClick={openNotif}
          style={{ position: 'relative', background: 'none', border: 'none', padding: 0, cursor: 'pointer', flexShrink: 0 }}
        >
          <img src="logo_80.png" alt="Sauv'Moi" style={{ width: 38, height: 38, objectFit: 'contain', borderRadius: 10, display: 'block' }} />
          {unreadCount > 0 && (
            <div style={{
              position: 'absolute', top: -5, right: -5,
              width: 18, height: 18, borderRadius: '50%',
              background: 'var(--sm-red)', color: 'white',
              fontSize: 10, fontWeight: 700,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              border: '2px solid white',
              fontFamily: 'var(--font-ui)',
            }}>
              {unreadCount > 9 ? '9+' : unreadCount}
            </div>
          )}
        </button>

        {/* Salutation */}
        <div style={{ flex: 1, minWidth: 0 }}>
          <h1 className="sm-serif" style={{ fontSize: 21, lineHeight: 1.15, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {hour < 13 ? t('home.greeting_morning') : t('home.greeting_evening')} {prenom}
          </h1>
          <p style={{ fontSize: 12.5, color: 'var(--sm-ink-500)', marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {t('splash.tagline')}
          </p>
        </div>

        {/* Avatar cliquable → profil */}
        <button
          onClick={() => nav.go('profile')}
          style={{ background: 'none', border: 'none', padding: 0, cursor: 'pointer', flexShrink: 0 }}
        >
          {user?.photo ? (
            <img
              src={user.photo}
              alt="avatar"
              style={{ width: 38, height: 38, borderRadius: '50%', objectFit: 'cover', border: '2px solid white', boxShadow: '0 0 0 1.5px var(--sm-line)' }}
            />
          ) : (
            <div style={{
              width: 38, height: 38, borderRadius: '50%',
              background: avatarBg, color: 'white',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 13, fontWeight: 700, letterSpacing: '0.02em',
            }}>
              {initials}
            </div>
          )}
        </button>
      </div>

      {/* ── Corps scrollable ────────────────────────────────────────────── */}
      {/* Lot 6 avait comblé le vide du bas avec justifyContent:'space-between',
          ce qui écartait les blocs les uns des autres au lieu de se contenter
          d'agrandir la marge finale — des trous irréguliers ENTRE les cartes,
          plus relâché qu'organisé. Rythme constant (`gap`) entre des blocs
          ancrés en haut ; l'espace qui reste après le dernier bloc devient
          une marge basse (padding-bottom du conteneur), délibérée plutôt que
          subie. Les deux nouveaux blocs ci-dessous (numéros d'urgence,
          reprise de formation) réduisent d'eux-mêmes cet espace résiduel en
          donnant un contenu utile à afficher plutôt que de le combler
          artificiellement. */}
      <div style={{ flex: 1, overflowY: 'auto', padding: '18px 18px 28px', background: 'var(--sm-paper)', display: 'flex', flexDirection: 'column', gap: 20 }}>

        {/* Grande carte Chat IA — photo réelle + voile bleu marine pour la
            lisibilité du texte (blanc, y compris en anglais). Le fond uni
            --sm-navy-deep sert de repli le temps que l'image charge (pas de
            flash blanc). sm-card-breathe : respiration douce du box-shadow
            pour attirer l'attention sans agressivité — recolorée en navy
            (voir styles.css) pour rester cohérente avec ce nouveau fond. Le
            bouton photo (tap n'importe où sur la carte) et le micro rond
            sont deux éléments FRÈRES superposés (pas un bouton imbriqué
            dans un bouton) : le micro, positionné après dans le DOM,
            reçoit les clics dans sa zone en priorité. */}
        <div
          className="sm-card-breathe"
          style={{
            position: 'relative', width: '100%', minHeight: 148, flexShrink: 0,
            borderRadius: 'var(--sm-radius)',
            overflow: 'hidden', background: 'var(--sm-navy-deep)',
          }}
        >
          <button
            onClick={() => nav.go('chat')}
            style={{
              position: 'absolute', inset: 0, width: '100%', height: '100%',
              border: 'none', cursor: 'pointer', textAlign: 'left', padding: 18,
              display: 'flex', flexDirection: 'column', justifyContent: 'space-between', gap: 10,
              backgroundImage: 'linear-gradient(var(--sm-navy-deep-soft), var(--sm-navy-deep-soft)), url(\'https://images.pexels.com/photos/20100296/pexels-photo-20100296.jpeg?auto=compress&cs=tinysrgb&w=1200\')',
              backgroundSize: 'cover', backgroundPosition: 'center',
            }}
          >
            <span className="sm-pill-badge">{t('home.today_badge')}</span>
            <div style={{ maxWidth: '78%' }}>
              <h2 className="sm-serif" style={{ fontSize: 21, fontWeight: 700, color: 'white', marginBottom: 8, lineHeight: 1.2 }}>
                {t('home.chat_card_title')}
              </h2>
              <p style={{ fontSize: 13.5, color: 'rgba(255,255,255,0.85)', lineHeight: 1.5 }}>
                {t('home.chat_card_subtitle')}
              </p>
            </div>
          </button>

          {/* Trait vert discret */}
          <div style={{ position: 'absolute', bottom: 16, left: 18, width: 26, height: 3, borderRadius: 2, background: 'var(--sm-green)' }} />

          {/* Micro rouge — fonctionnel : ouvre le chat directement en mode
              vocal continu (enterVoiceMode existant dans live-chat.jsx),
              plutôt qu'un simple raccourci visuel vers l'écran texte. */}
          <button
            onClick={(e) => { e.stopPropagation(); window.SM.autoVoiceMode = true; nav.go('chat'); }}
            aria-label={t('chat.mic_voice_input_title')}
            style={{
              position: 'absolute', right: 16, bottom: 14, zIndex: 1,
              width: 52, height: 52, borderRadius: '50%', flexShrink: 0,
              background: 'var(--sm-red)', border: 'none', cursor: 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              boxShadow: '0 4px 16px rgba(229,57,53,0.45)',
            }}
          >
            <Icon name="mic" size={23} color="white" strokeWidth={2} />
          </button>
        </div>

        {/* Carte Scanner QR — fond blanc (gris clair en sombre, via la
            règle .sm-dark [style*="background: white"] déjà en place) */}
        <button
          onClick={() => nav.go('qr_scanner')}
          style={{
            display: 'flex', width: '100%', alignItems: 'center', gap: 14, flexShrink: 0,
            padding: '15px 16px', borderRadius: 'var(--sm-radius)',
            background: 'white',
            cursor: 'pointer', textAlign: 'left',
            boxShadow: '0 2px 8px rgba(10,22,40,0.06)',
          }}
        >
          <div className="sm-icon-tile" style={{ background: 'var(--sm-blue-soft)' }}>
            <Icon name="qr-code" size={22} color="var(--sm-blue)" strokeWidth={1.9} />
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="sm-serif" style={{ fontSize: 16, color: 'var(--sm-ink)', marginBottom: 3 }}>
              {t('home.qr_scan_title')}
            </div>
            <div style={{ fontSize: 13, color: 'var(--sm-ink-500)' }}>
              {t('home.qr_scan_subtitle')}
            </div>
          </div>
          <div className="sm-icon-circle" style={{ background: 'var(--sm-blue-soft)' }}>
            <Icon name="arrow-right" size={16} color="var(--sm-blue)" strokeWidth={2} />
          </div>
        </button>

        {/* Numéros d'urgence en appel direct — réutilise EmergencyQuickNumbers
            (live-sos.jsx, même composant que l'écran SOS, pas de copie avec
            ses propres numéros) : l'action la plus urgente que l'app puisse
            offrir ne doit pas demander de passer par SOS d'abord. */}
        <div style={{ flexShrink: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', marginBottom: 12 }}>
            <Icon name="phone-call" size={17} color="var(--sm-red)" strokeWidth={2} style={{ marginRight: 8 }} />
            <h3 className="sm-serif" style={{ fontSize: 18 }}>{t('sos.emergency_numbers')}</h3>
          </div>
          <EmergencyQuickNumbers t={t} />
        </div>

        {/* Reprise de formation — module suivant + progression, données déjà
            disponibles via l'API formation (même source que screen-training.jsx). */}
        <TrainingResumeCard nav={nav} t={t} lang={currentLang} />

        {/* Titre + carte groupés dans un seul bloc flex pour que le titre
            reste toujours collé à sa carte quel que soit l'espace disponible. */}
        <div style={{ flexShrink: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', marginBottom: 12 }}>
            <Icon name="lightbulb" size={17} color="var(--sm-ink)" strokeWidth={2} style={{ marginRight: 8 }} />
            <h3 className="sm-serif" style={{ fontSize: 18 }}>{t('home.tip_of_day')}</h3>
          </div>
          <TipOfDayCard tip={tip} />
        </div>
      </div>

      <FloatingChatButton nav={nav} />

      {/* ── Barre de navigation bleue foncée ───────────────────────────── */}
      <HomeTabBar active="home" nav={nav} />

      {/* ── Bottom sheet notifications ───────────────────────────────────── */}
      {showNotifs && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 200, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end' }}>
          {/* Backdrop */}
          <div
            onClick={() => setShowNotifs(false)}
            style={{ flex: 1, background: 'rgba(10,22,40,0.4)' }}
          />
          {/* Sheet */}
          <div style={{ background: 'white', borderRadius: '20px 20px 0 0', maxHeight: '78%', display: 'flex', flexDirection: 'column', boxShadow: '0 -4px 30px rgba(0,0,0,0.12)' }}>
            {/* Handle */}
            <div style={{ width: 40, height: 4, borderRadius: 2, background: '#E0E0E0', margin: '12px auto 0', flexShrink: 0 }} />
            {/* Header sheet */}
            <div style={{ padding: '14px 20px 12px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexShrink: 0, borderBottom: '1px solid var(--sm-line)' }}>
              <h2 className="sm-serif" style={{ fontSize: 18 }}>{t('home.notifications_title')}</h2>
              <button onClick={() => setShowNotifs(false)} style={{ background: 'none', border: 'none', padding: '4px', cursor: 'pointer' }}>
                <Icon name="x" size={20} color="var(--sm-ink-400)" />
              </button>
            </div>
            {/* Liste */}
            <div style={{ flex: 1, overflowY: 'auto', padding: '12px 16px 32px' }}>
              {notifs.length === 0 ? (
                <div style={{ textAlign: 'center', padding: '36px 20px', color: 'var(--sm-ink-500)', fontSize: 14 }}>
                  {t('home.no_notifications')}
                </div>
              ) : notifs.map(n => (
                <div key={n.id} style={{
                  padding: '14px 16px', borderRadius: 'var(--sm-radius)',
                  background: 'white', boxShadow: 'var(--sm-shadow)',
                  marginBottom: 10, display: 'flex', gap: 12, alignItems: 'flex-start',
                  opacity: n.read ? 0.65 : 1,
                }}>
                  <div style={{ width: 42, height: 42, borderRadius: 12, background: 'var(--sm-red-soft)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                    <Icon name="siren" size={20} color="var(--sm-red)" />
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--sm-ink)', lineHeight: 1.4, fontFamily: 'var(--font-ui)' }}>{n.message}</div>
                    <div style={{ fontSize: 12, color: 'var(--sm-ink-500)', marginTop: 4 }}>
                      {new Date(n.createdAt).toLocaleString('fr-FR', { hour: '2-digit', minute: '2-digit', day: '2-digit', month: 'short' })}
                    </div>
                    {n.lat != null && n.lng != null && (
                      <a
                        href={'https://maps.google.com/?q=' + n.lat + ',' + n.lng}
                        target="_blank" rel="noopener noreferrer"
                        style={{ display: 'inline-flex', alignItems: 'center', gap: 4, marginTop: 8, fontSize: 13, color: 'var(--sm-blue)', textDecoration: 'none', fontWeight: 500 }}
                      >
                        <Icon name="map-pin" size={13} color="var(--sm-blue)" />
                        {t('home.view_on_map')}
                      </a>
                    )}
                  </div>
                  {!n.read && (
                    <div style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--sm-red)', flexShrink: 0, marginTop: 5 }} />
                  )}
                </div>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ════════════════════════════════════════════════════════════════════════════
// ÉCRAN QR SCANNER (caméra branchée via Capacitor Camera plugin)
// ════════════════════════════════════════════════════════════════════════════
function QrScannerScreen({ nav }) {
  useLucide();
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', background: '#0a1628' }}>

      {/* Header */}
      <div style={{ padding: '18px 20px 12px', display: 'flex', alignItems: 'center', gap: 12 }}>
        <button
          onClick={() => nav.back()}
          style={{ padding: 8, margin: -8, background: 'none', border: 'none', cursor: 'pointer' }}
        >
          <Icon name="arrow-left" size={22} color="white" />
        </button>
        <h2 className="sm-serif" style={{ fontSize: 20, color: 'white' }}>
          Scanner un QR Sauv'Moi
        </h2>
      </div>

      {/* Zone de visée */}
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '24px 40px' }}>
        <div style={{
          width: 220, height: 220, borderRadius: 24, marginBottom: 32,
          border: '1.5px solid rgba(255,255,255,0.15)',
          background: 'rgba(255,255,255,0.04)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          position: 'relative',
        }}>
          {/* Coins du viseur */}
          <div style={{ position: 'absolute', top: 14, left: 14, width: 26, height: 26, borderTop: '3px solid white', borderLeft: '3px solid white', borderRadius: '8px 0 0 0' }} />
          <div style={{ position: 'absolute', top: 14, right: 14, width: 26, height: 26, borderTop: '3px solid white', borderRight: '3px solid white', borderRadius: '0 8px 0 0' }} />
          <div style={{ position: 'absolute', bottom: 14, left: 14, width: 26, height: 26, borderBottom: '3px solid white', borderLeft: '3px solid white', borderRadius: '0 0 0 8px' }} />
          <div style={{ position: 'absolute', bottom: 14, right: 14, width: 26, height: 26, borderBottom: '3px solid white', borderRight: '3px solid white', borderRadius: '0 0 8px 0' }} />
          <Icon name="camera-off" size={52} color="rgba(255,255,255,0.2)" />
        </div>

        <h3 className="sm-serif" style={{ fontSize: 22, color: 'white', marginBottom: 12, textAlign: 'center' }}>
          Caméra non activée
        </h3>
        <p style={{ fontSize: 14, color: 'rgba(255,255,255,0.55)', textAlign: 'center', lineHeight: 1.6, marginBottom: 8 }}>
          Fonctionnalité caméra à activer via le plugin Capacitor Camera
        </p>
        <code style={{
          fontFamily: 'var(--font-mono)', fontSize: 12,
          color: 'rgba(255,255,255,0.75)',
          background: 'rgba(255,255,255,0.08)',
          padding: '6px 12px', borderRadius: 8,
        }}>
          @capacitor/camera
        </code>
      </div>

      <div style={{ padding: '0 24px 48px' }}>
        <button onClick={() => nav.back()} className="sm-btn sm-btn-outline-white" style={{ width: '100%' }}>
          Retour
        </button>
      </div>
    </div>
  );
}

// ════════════════════════════════════════════════════════════════════════════
// DESKTOP (inchangé — canvas design uniquement)
// ════════════════════════════════════════════════════════════════════════════
function QuickTile({ color, tint, icon, title, sub, onClick }) {
  return (
    <button onClick={onClick} className="sm-card" style={{
      padding: 16, textAlign: 'left',
      display: 'flex', flexDirection: 'column', gap: 10,
      cursor: 'pointer', background: 'white',
      transition: 'transform 50ms var(--ease), filter 150ms var(--ease)',
    }}>
      <div style={{ width: 40, height: 40, borderRadius: 12, background: color, color: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Icon name={icon} size={22} strokeWidth={2} />
      </div>
      <div>
        <div className="sm-serif" style={{ fontSize: 16, color: 'var(--sm-ink)' }}>{title}</div>
        <div style={{ fontSize: 12, color: 'var(--sm-ink-500)', marginTop: 2 }}>{sub}</div>
      </div>
    </button>
  );
}

function BigQuick({ color, icon, title, sub, extra, onClick }) {
  return (
    <button onClick={onClick} className="sm-card" style={{ padding: 22, textAlign: 'left', display: 'flex', flexDirection: 'column', gap: 14, cursor: 'pointer', background: 'white' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <div style={{ width: 44, height: 44, borderRadius: 12, background: color, color: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name={icon} size={22} strokeWidth={2} />
        </div>
        {extra && <span className="sm-serif" style={{ fontSize: 26, color: color, lineHeight: 1 }}>{extra}</span>}
      </div>
      <div>
        <div className="sm-serif" style={{ fontSize: 19, marginBottom: 4 }}>{title}</div>
        <div style={{ fontSize: 13, color: 'var(--sm-ink-500)' }}>{sub}</div>
      </div>
    </button>
  );
}

function Sidebar({ active, onNav }) {
  const items = [
    { id: 'home',      label: 'Accueil',        icon: 'home' },
    { id: 'chat',      label: 'Chat IA',        icon: 'sparkles' },
    { id: 'training',  label: 'Formations',     icon: 'graduation-cap' },
    { id: 'records',   label: 'Carnet médical', icon: 'notebook-pen' },
    { id: 'rescuers',  label: 'Secouristes',    icon: 'map-pin' },
    { id: 'profile',   label: 'Profil',         icon: 'user' },
  ];
  return (
    <aside className="sm-sidebar">
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '4px 12px 14px' }}>
        <div style={{ width: 32, height: 32, borderRadius: 8, background: 'var(--sm-ink)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name="life-buoy" size={20} color="var(--sm-paper)" />
        </div>
        <span className="sm-serif" style={{ fontSize: 21, letterSpacing: '-0.02em' }}>Sauv'Moi</span>
      </div>
      {items.map(it => (
        <button key={it.id} className={'sm-sidebar-item' + (it.id === active ? ' is-active' : '')} onClick={() => onNav(it.id)}>
          <Icon name={it.icon} size={18} />
          <span>{it.label}</span>
        </button>
      ))}
      <div style={{ marginTop: 'auto' }}>
        <button
          onClick={() => onNav('sos')}
          style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 12, padding: '14px 14px', borderRadius: 10, background: 'var(--sm-red)', color: 'white', border: 'none', textAlign: 'left', cursor: 'pointer' }}
        >
          <div style={{ width: 36, height: 36, borderRadius: '50%', background: 'rgba(255,255,255,.18)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name="siren" size={20} strokeWidth={2} />
          </div>
          <div style={{ lineHeight: 1.2 }}>
            <div style={{ fontWeight: 700, fontSize: 14 }}>Déclencher SOS</div>
            <div style={{ fontSize: 11, opacity: 0.8 }}>3 sec d'appui long</div>
          </div>
        </button>
        <div style={{ padding: '12px 12px 0', fontSize: 11, color: 'var(--sm-ink-500)', lineHeight: 1.4 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--sm-green)' }} /> En ligne · Abidjan
          </div>
          <div style={{ marginTop: 4 }}>v1.0 · démo hackathon</div>
        </div>
      </div>
    </aside>
  );
}

function HomeDesktop({ nav, lang }) {
  useLucide();
  return (
    <>
      <Sidebar active="home" onNav={(id) => nav.go(id)} />
      <div style={{ flex: 1, minWidth: 0, overflowY: 'auto', padding: '28px 48px 48px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 28 }}>
          <div>
            <div style={{ fontSize: 13, color: 'var(--sm-ink-500)' }}>Abidjan · Sauv'Moi</div>
            <h1 className="sm-serif" style={{ fontSize: 34, marginTop: 4 }}>{T('hello', lang)}</h1>
          </div>
          <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 16px', borderRadius: 999, border: '1px solid var(--sm-line)', background: 'white', minWidth: 320 }}>
              <Icon name="search" size={18} color="var(--sm-ink-500)" />
              <span style={{ color: 'var(--sm-ink-500)', fontSize: 14 }}>Rechercher un geste, une fiche…</span>
              <span style={{ marginLeft: 'auto', fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--sm-ink-400)' }}>⌘K</span>
            </div>
            <LangPill lang={lang} />
            <button style={{ width: 40, height: 40, borderRadius: '50%', border: '1px solid var(--sm-line)', display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'white', cursor: 'pointer' }}>
              <Icon name="bell" size={18} />
            </button>
            <div className="sm-photo-placeholder" style={{ width: 40, height: 40, borderRadius: '50%' }}>
              <span style={{ position: 'relative', zIndex: 1, fontWeight: 600 }}>AK</span>
            </div>
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '6fr 4fr', gap: 20, marginBottom: 20 }}>
          <div className="sm-card" style={{ padding: 36, display: 'flex', gap: 24, alignItems: 'center', minHeight: 240 }}>
            <div style={{ flex: 1 }}>
              <div className="sm-eyebrow" style={{ marginBottom: 10, color: 'var(--sm-blue)' }}><Icon name="sparkles" size={12} /> Sauv'Moi écoute</div>
              <h2 className="sm-serif" style={{ fontSize: 38, marginBottom: 10, letterSpacing: '-0.02em' }}>{T('whats_happening', lang)}</h2>
              <p style={{ color: 'var(--sm-ink-500)', fontSize: 15, marginBottom: 18, fontStyle: 'italic' }}>{T('whats_examples', lang)}</p>
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                {['Quelqu\'un saigne', 'Il s\'étouffe', 'Brûlure'].map(s => (
                  <button key={s} onClick={() => nav.go('chat')} className="sm-chip"><Icon name="quote" size={12} /> {s}</button>
                ))}
              </div>
            </div>
            <button onClick={() => nav.go('chat')} style={{ position: 'relative', width: 132, height: 132, flexShrink: 0 }}>
              <PulseCircle size={132}><Icon name="mic" size={48} strokeWidth={2} /></PulseCircle>
            </button>
          </div>
          <div className="sm-card" style={{ overflow: 'hidden', padding: 0, display: 'flex', flexDirection: 'column' }}>
            <div className="sm-photo-placeholder" style={{ height: 140 }}><Icon name="heart-pulse" size={48} /></div>
            <div style={{ padding: 20, display: 'flex', flexDirection: 'column', gap: 8, flex: 1 }}>
              <div className="sm-eyebrow" style={{ color: 'var(--sm-green)' }}>{T('tip_of_day', lang)}</div>
              <h3 className="sm-serif" style={{ fontSize: 22 }}>{T('pls', lang)}</h3>
              <p style={{ fontSize: 13, color: 'var(--sm-ink-500)' }}>Pour une personne inconsciente qui respire.</p>
              <div style={{ marginTop: 'auto', display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingTop: 10 }}>
                <span style={{ fontSize: 12, color: 'var(--sm-ink-500)' }}>{T('read_by', lang)}</span>
                <button className="sm-btn sm-btn-ghost" style={{ padding: '6px 10px', minHeight: 32, fontSize: 13 }}>Lire <Icon name="arrow-right" size={14} /></button>
              </div>
            </div>
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 20 }}>
          <BigQuick color="var(--sm-green)" icon="graduation-cap"  title="Formation en cours"        sub="PSC1 · module 6 / 10" extra="58 %" onClick={() => nav.go('training')} />
          <BigQuick color="var(--sm-ink)"   icon="notebook-pen"    title="Carnet médical"            sub="groupe O+ · allergies 2"         onClick={() => null} />
          <BigQuick color="var(--sm-blue)"  icon="map-pin"         title="Secouristes près"          sub="12 actifs · 200 m"               onClick={() => null} />
        </div>
      </div>
    </>
  );
}

Object.assign(window, { HomeMobile, HomeDesktop, Sidebar, QrScannerScreen, HomeTabBar });
