// AlertsPage — Page de gestion des alertes email sauvegardées
// Route : #/alertes
// Gating : bouton "Sauver comme alerte" réservé Investisseur+
// Stockage local : localStorage clé 'vestora_saved_alerts'

(function () {
  const { useState: useAPS, useEffect: useAPE } = React;

  const STORAGE_KEY = 'vestora_saved_alerts';

  // ---- Helpers localStorage ----
  function loadAlerts() {
    try {
      const raw = localStorage.getItem(STORAGE_KEY);
      return raw ? JSON.parse(raw) : [];
    } catch {
      return [];
    }
  }

  function saveAlerts(alerts) {
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(alerts));
    } catch (e) {
      console.warn('[alerts] Impossible de sauver dans localStorage', e);
    }
  }

  function generateId() {
    return `alert_${Date.now()}_${Math.random().toString(36).slice(2, 7)}`;
  }

  // ---- Toast interne ----
  function Toast({ msg, onDone }) {
    useAPE(() => {
      const t = setTimeout(onDone, 3500);
      return () => clearTimeout(t);
    }, []);

    return (
      <div style={{
        position: 'fixed',
        bottom: 90,
        left: '50%',
        transform: 'translateX(-50%)',
        zIndex: 9999,
        background: 'var(--ink-1, #1a1a1a)',
        color: '#fff',
        padding: '10px 20px',
        borderRadius: 8,
        fontSize: 13.5,
        fontWeight: 500,
        boxShadow: '0 4px 16px rgba(0,0,0,0.25)',
        maxWidth: 380,
        textAlign: 'center',
        animation: 'pwFadeIn 0.2s ease',
        fontFamily: 'var(--font-body, Inter, sans-serif)',
      }}>
        {msg}
      </div>
    );
  }

  // ---- Modale "Nommer l'alerte" (accès Investisseur+) ----
  function SaveAlertModal({ open, onClose, onSave, initialName }) {
    const [name, setName] = useAPS(initialName || '');
    const [freq, setFreq] = useAPS('daily');

    useAPE(() => {
      if (open) setName(initialName || '');
    }, [open, initialName]);

    useAPE(() => {
      if (!open) return;
      const handleKey = (e) => { if (e.key === 'Escape') onClose(); };
      document.addEventListener('keydown', handleKey);
      return () => document.removeEventListener('keydown', handleKey);
    }, [open, onClose]);

    if (!open) return null;

    return (
      <div
        style={{
          position: 'fixed', inset: 0, zIndex: 10000,
          background: 'rgba(0,0,0,0.5)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          padding: 16,
          backdropFilter: 'blur(2px)',
          animation: 'pwFadeIn 0.15s ease',
        }}
        onClick={e => { if (e.target === e.currentTarget) onClose(); }}
        role="dialog"
        aria-modal="true"
        aria-label="Nommer votre alerte"
      >
        <div
          style={{
            background: 'var(--bg-elev, #fff)',
            borderRadius: 14,
            boxShadow: '0 20px 60px rgba(0,0,0,0.22)',
            width: '100%',
            maxWidth: 420,
            padding: '28px 24px 24px',
            fontFamily: 'var(--font-body, Inter, sans-serif)',
            color: 'var(--ink-1, #1a1a1a)',
            animation: 'pwSlideUp 0.2s ease',
          }}
          onClick={e => e.stopPropagation()}
        >
          <h2 style={{
            fontFamily: 'var(--serif, Fraunces, serif)',
            fontSize: 18, fontWeight: 500,
            margin: '0 0 20px',
            letterSpacing: '-0.01em',
          }}>
            Nommer votre alerte
          </h2>

          <label style={{ display: 'block', marginBottom: 16 }}>
            <span style={{ fontSize: 13, fontWeight: 500, color: 'var(--ink-2, #555)', display: 'block', marginBottom: 6 }}>
              Nom de l'alerte
            </span>
            <input
              type="text"
              value={name}
              onChange={e => setName(e.target.value)}
              placeholder="ex. Plex Lévis cap rate 6%+"
              maxLength={80}
              autoFocus
              style={{
                width: '100%',
                padding: '9px 12px',
                borderRadius: 8,
                border: '1.5px solid var(--line, #e8e8e0)',
                fontSize: 14,
                fontFamily: 'inherit',
                color: 'var(--ink-1, #1a1a1a)',
                background: 'var(--bg, #fff)',
                outline: 'none',
                boxSizing: 'border-box',
                transition: 'border-color 0.15s',
              }}
              onFocus={e => { e.currentTarget.style.borderColor = 'var(--accent, oklch(0.36 0.07 155))'; }}
              onBlur={e => { e.currentTarget.style.borderColor = 'var(--line, #e8e8e0)'; }}
            />
          </label>

          <label style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 24, cursor: 'pointer' }}>
            <input
              type="checkbox"
              checked={freq === 'daily'}
              onChange={e => setFreq(e.target.checked ? 'daily' : 'none')}
              style={{ width: 16, height: 16, cursor: 'pointer', accentColor: 'var(--accent, oklch(0.36 0.07 155))' }}
            />
            <span style={{ fontSize: 13.5, color: 'var(--ink-1, #1a1a1a)' }}>
              Recevoir un récapitulatif quotidien par email
            </span>
          </label>

          {/* Banner honnête */}
          <div style={{
            background: 'var(--bg-warm, #f9f9f6)',
            border: '1px solid var(--line, #e8e8e0)',
            borderRadius: 8,
            padding: '10px 12px',
            fontSize: 12.5,
            color: 'var(--ink-2, #666)',
            marginBottom: 20,
            lineHeight: 1.5,
          }}>
            🚧 Envoi email actif dès le branchement de notre flux de données (mai 2026).
            Vos alertes sont sauvegardées et seront activées automatiquement.
          </div>

          <div style={{ display: 'flex', gap: 10 }}>
            <button
              onClick={() => {
                if (name.trim()) onSave(name.trim(), freq);
              }}
              disabled={!name.trim()}
              style={{
                flex: 1,
                padding: '11px 16px',
                borderRadius: 8,
                border: 'none',
                background: name.trim() ? 'var(--accent, oklch(0.36 0.07 155))' : 'var(--line, #e0e0d8)',
                color: name.trim() ? '#fff' : 'var(--ink-3, #aaa)',
                fontWeight: 600, fontSize: 14,
                cursor: name.trim() ? 'pointer' : 'not-allowed',
                fontFamily: 'inherit',
                transition: 'opacity 0.15s',
              }}
            >
              Sauvegarder
            </button>
            <button
              onClick={onClose}
              style={{
                padding: '11px 16px',
                borderRadius: 8,
                border: '1.5px solid var(--line, #e8e8e0)',
                background: 'transparent',
                color: 'var(--ink-2, #555)',
                fontWeight: 500, fontSize: 14,
                cursor: 'pointer', fontFamily: 'inherit',
              }}
            >
              Annuler
            </button>
          </div>
        </div>
      </div>
    );
  }

  // ---- Carte d'alerte ----
  function AlertCard({ alert, onPause, onDelete, onApply }) {
    const [confirmDelete, setConfirmDelete] = useAPS(false);

    const freqLabel = alert.freq === 'daily' ? 'Quotidien' : 'Aucun email';
    const statusColor = alert.paused
      ? 'var(--ink-3, #aaa)'
      : 'var(--accent, oklch(0.36 0.07 155))';

    return (
      <div className="alert-card">
        <div className="alert-card-body">
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, flex: 1, minWidth: 0 }}>
            {/* Indicateur statut */}
            <div style={{
              flexShrink: 0,
              width: 10, height: 10,
              borderRadius: '50%',
              background: statusColor,
              marginTop: 5,
              boxShadow: alert.paused ? 'none' : `0 0 0 3px oklch(0.36 0.07 155 / 0.15)`,
            }} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="alert-card-name">{alert.name}</div>
              <div className="alert-card-meta">
                <span>{freqLabel}</span>
                <span className="alert-card-dot">·</span>
                <span>Créée le {new Date(alert.createdAt).toLocaleDateString('fr-CA')}</span>
                {alert.paused && (
                  <>
                    <span className="alert-card-dot">·</span>
                    <span style={{ color: 'var(--ink-3, #aaa)', fontStyle: 'italic' }}>En pause</span>
                  </>
                )}
              </div>
              {/* Banner email si freq=daily */}
              {alert.freq === 'daily' && !alert.paused && (
                <div style={{
                  marginTop: 6,
                  fontSize: 11.5,
                  color: 'var(--ink-3, #888)',
                  fontStyle: 'italic',
                }}>
                  🚧 Envois activés au lancement du flux de données
                </div>
              )}
            </div>
          </div>

          {/* Actions */}
          <div className="alert-card-actions">
            <button
              className="alert-action-btn"
              onClick={() => onApply(alert)}
              title="Appliquer ces filtres"
            >
              <svg width="14" height="14" viewBox="0 0 14 14" stroke="currentColor" strokeWidth="1.4" fill="none" aria-hidden="true">
                <circle cx="6" cy="6" r="4"/>
                <path d="M10 10l2.5 2.5"/>
              </svg>
              Filtres
            </button>
            <button
              className="alert-action-btn"
              onClick={() => onPause(alert.id)}
              title={alert.paused ? 'Réactiver' : 'Mettre en pause'}
            >
              {alert.paused ? (
                <svg width="14" height="14" viewBox="0 0 14 14" stroke="currentColor" strokeWidth="1.4" fill="none" aria-hidden="true">
                  <polygon points="4,2 12,7 4,12" fill="currentColor" stroke="none"/>
                </svg>
              ) : (
                <svg width="14" height="14" viewBox="0 0 14 14" stroke="currentColor" strokeWidth="1.4" fill="none" aria-hidden="true">
                  <rect x="3" y="2" width="3" height="10" rx="1" fill="currentColor" stroke="none"/>
                  <rect x="8" y="2" width="3" height="10" rx="1" fill="currentColor" stroke="none"/>
                </svg>
              )}
              {alert.paused ? 'Reprendre' : 'Pause'}
            </button>
            {confirmDelete ? (
              <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <button
                  className="alert-action-btn alert-action-btn--danger"
                  onClick={() => onDelete(alert.id)}
                >
                  Confirmer
                </button>
                <button className="alert-action-btn" onClick={() => setConfirmDelete(false)}>
                  Annuler
                </button>
              </span>
            ) : (
              <button
                className="alert-action-btn alert-action-btn--danger"
                onClick={() => setConfirmDelete(true)}
                title="Supprimer l'alerte"
              >
                <svg width="14" height="14" viewBox="0 0 14 14" stroke="currentColor" strokeWidth="1.4" fill="none" aria-hidden="true">
                  <polyline points="2,4 12,4"/>
                  <path d="M5 4V2.5a.5.5 0 01.5-.5h3a.5.5 0 01.5.5V4"/>
                  <rect x="3" y="4" width="8" height="8" rx="1"/>
                </svg>
                Supprimer
              </button>
            )}
          </div>
        </div>
      </div>
    );
  }

  // ---- Page principale ----
  function AlertsPage({ lang, onBack, currentUser, currentFilters }) {
    const [alerts, setAlerts] = useAPS(() => loadAlerts());
    const [paywallOpen, setPaywallOpen] = useAPS(false);
    const [saveModalOpen, setSaveModalOpen] = useAPS(false);
    const [toast, setToast] = useAPS(null);

    // Tier courant
    const [tier, setTier] = useAPS('decouverte');
    useAPE(() => {
      const tg = window.vestora && window.vestora.tierGate;
      if (!tg) return;
      tg.getCurrentTier().then(t => setTier(t)).catch(() => setTier('decouverte'));
    }, [currentUser]);

    // SEO
    useAPE(() => {
      const prev = document.title;
      document.title = 'Mes alertes — Vestora';
      window.scrollTo(0, 0);
      return () => { document.title = prev; };
    }, []);

    const canUseAlerts = tier === 'investisseur' || tier === 'pro' || tier === 'entreprise';

    const showToast = (msg) => {
      setToast(msg);
    };

    const handleSaveClick = () => {
      if (!canUseAlerts) {
        setPaywallOpen(true);
      } else {
        setSaveModalOpen(true);
      }
    };

    const handleSave = (name, freq) => {
      const newAlert = {
        id: generateId(),
        name,
        filters: currentFilters || {},
        freq,
        paused: false,
        createdAt: new Date().toISOString(),
      };
      const updated = [newAlert, ...alerts];
      setAlerts(updated);
      saveAlerts(updated);
      setSaveModalOpen(false);
      showToast('Alerte sauvegardée ✓');
    };

    const handlePause = (id) => {
      const updated = alerts.map(a =>
        a.id === id ? { ...a, paused: !a.paused } : a
      );
      setAlerts(updated);
      saveAlerts(updated);
    };

    const handleDelete = (id) => {
      const updated = alerts.filter(a => a.id !== id);
      setAlerts(updated);
      saveAlerts(updated);
      showToast('Alerte supprimée');
    };

    const handleApply = (alert) => {
      // Redirige vers l'accueil — les filtres seront appliqués via URL ou état global futur
      // Pour l'instant, on navigue simplement vers l'accueil
      showToast('Filtres rappelés — retournez à l\'accueil pour les appliquer');
      setTimeout(() => window.navigateTo('#/'), 1200);
    };

    return (
      <div className="alerts-page">
        {/* Header */}
        <div className="alerts-page-header">
          <button className="btn btn-ghost" onClick={onBack}>← Retour</button>
          <div className="alerts-page-hero">
            <h1 className="alerts-page-title">Mes alertes</h1>
            <p className="alerts-page-subtitle">
              Sauvegardez vos recherches et recevez les nouvelles correspondances par email
            </p>
          </div>
          <div className="alerts-page-actions">
            <button
              className="btn alerts-save-btn"
              onClick={handleSaveClick}
              style={{
                display: 'inline-flex',
                alignItems: 'center',
                gap: 8,
                padding: '10px 18px',
                background: 'var(--accent, oklch(0.36 0.07 155))',
                color: '#fff',
                border: 'none',
                borderRadius: 8,
                fontWeight: 600,
                fontSize: 14,
                cursor: 'pointer',
                fontFamily: 'inherit',
                transition: 'opacity 0.15s',
              }}
              onMouseEnter={e => { e.currentTarget.style.opacity = '0.88'; }}
              onMouseLeave={e => { e.currentTarget.style.opacity = '1'; }}
            >
              {!canUseAlerts && (
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
                  <rect x="3" y="11" width="18" height="11" rx="2"/>
                  <path d="M7 11V7a5 5 0 0110 0v4"/>
                </svg>
              )}
              🔔 Sauver comme alerte
              {!canUseAlerts && (
                <span style={{
                  background: 'rgba(255,255,255,0.2)',
                  borderRadius: 4,
                  padding: '1px 6px',
                  fontSize: 11,
                  fontWeight: 600,
                  letterSpacing: '0.03em',
                }}>
                  Investisseur+
                </span>
              )}
            </button>
          </div>
        </div>

        {/* Banner info */}
        <div className="alerts-banner">
          <div style={{
            background: 'oklch(0.96 0.04 90 / 0.5)',
            border: '1px solid oklch(0.85 0.08 90)',
            borderRadius: 10,
            padding: '12px 16px',
            fontSize: 13.5,
            color: 'var(--ink-1, #1a1a1a)',
            display: 'flex',
            alignItems: 'flex-start',
            gap: 10,
            maxWidth: 680,
          }}>
            <span style={{ fontSize: 16, flexShrink: 0, lineHeight: 1.3 }}>🚧</span>
            <div>
              <strong>Envoi email actif dès le branchement de notre flux de données (mai 2026).</strong>{' '}
              Vos alertes sont déjà sauvegardées et seront automatiquement activées quand le feed de données sera opérationnel.
              On vous préviendra dès que c'est en ligne.
            </div>
          </div>
        </div>

        {/* Liste des alertes */}
        <div className="alerts-list-container">
          {alerts.length === 0 ? (
            <div className="alerts-empty">
              <div className="alerts-empty-icon">
                <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="var(--ink-3, #ccc)" strokeWidth="1.2" aria-hidden="true">
                  <path d="M18 8A6 6 0 006 8c0 7-3 9-3 9h18s-3-2-3-9"/>
                  <path d="M13.73 21a2 2 0 01-3.46 0"/>
                </svg>
              </div>
              <p className="alerts-empty-title">Aucune alerte</p>
              <p className="alerts-empty-sub">
                Sauvegardez votre première recherche pour être notifié des nouvelles correspondances.
              </p>
              {canUseAlerts ? (
                <button
                  className="btn"
                  onClick={() => setSaveModalOpen(true)}
                  style={{
                    marginTop: 16,
                    padding: '10px 22px',
                    background: 'var(--accent, oklch(0.36 0.07 155))',
                    color: '#fff',
                    border: 'none',
                    borderRadius: 8,
                    fontWeight: 600,
                    cursor: 'pointer',
                    fontFamily: 'inherit',
                    fontSize: 14,
                  }}
                >
                  Créer une alerte
                </button>
              ) : (
                <button
                  className="btn"
                  onClick={() => setPaywallOpen(true)}
                  style={{
                    marginTop: 16,
                    padding: '10px 22px',
                    background: 'var(--accent, oklch(0.36 0.07 155))',
                    color: '#fff',
                    border: 'none',
                    borderRadius: 8,
                    fontWeight: 600,
                    cursor: 'pointer',
                    fontFamily: 'inherit',
                    fontSize: 14,
                  }}
                >
                  🔒 Débloquer les alertes
                </button>
              )}
            </div>
          ) : (
            <div className="alerts-list">
              {alerts.map(alert => (
                <AlertCard
                  key={alert.id}
                  alert={alert}
                  onPause={handlePause}
                  onDelete={handleDelete}
                  onApply={handleApply}
                />
              ))}
            </div>
          )}
        </div>

        {/* Paywall Modal */}
        {window.PaywallModal && (
          <window.PaywallModal
            open={paywallOpen}
            onClose={() => setPaywallOpen(false)}
            feature="alerts_multi"
            featureLabel="Alertes email multi-critères"
            requiredTier="investisseur"
            currentTier={tier}
            reason="tier_too_low"
          />
        )}

        {/* Save Modal */}
        <SaveAlertModal
          open={saveModalOpen}
          onClose={() => setSaveModalOpen(false)}
          onSave={handleSave}
          initialName={currentFilters ? 'Ma recherche' : ''}
        />

        {/* Toast */}
        {toast && <Toast msg={toast} onDone={() => setToast(null)} />}
      </div>
    );
  }

  window.AlertsPage = AlertsPage;
})();
