// web/loyalty-v2.jsx — Loyalty deep dashboard: Profile editor, settings, redemption modal
// [GOAL-SYNC 2026-07-08] Purge des démos user-facing : profil « Ikyes Benzaid » hardcodé →
// données RÉELLES (api.profile() + api.getPhone()), carte Visa ····4242 fictive → état vide
// honnête, préférences/allergènes fictifs retirés, « Se déconnecter » réellement câblé.
const { useState: lvS, useEffect: lvE } = React;

// [GOAL-SYNC 2026-07-08] Affichage FR d'un numéro stocké en chiffres ('0612345678' / '612345678')
// → '+33 6 12 34 56 78'. Même logique que frPhoneIntl (account-v2.jsx), locale à ce fichier.
function lvPhoneFr(raw) {
  const digits = String(raw || '').replace(/\D/g, '').replace(/^33/, '').replace(/^0/, '');
  if (!digits) return '';
  return '+33 ' + digits.replace(/(\d)(?=(\d{2})+$)/g, '$1 ').trim();
}

function ProfileEditor() {
  const api = (typeof window !== 'undefined' && window.LC && window.LC.api) || null;
  // [GOAL-SYNC 2026-07-08] Téléphone = source locale immédiate (api.getPhone) ; nom/email
  // complétés depuis GET /api/profile si le backend les renvoie. Aucune donnée inventée.
  const [u, setU] = lvS({ name: '', email: '', phone: (api && api.getPhone && api.getPhone()) || '' });
  lvE(() => {
    let live = true;
    if (api && api.profile) {
      api.profile()
        .then(p => { if (live && p) setU(prev => ({ ...prev, name: p.name || prev.name, email: p.email || prev.email, phone: p.phone || prev.phone })); })
        .catch(() => {}); // hors-ligne / token expiré → on garde le téléphone local, champs vides honnêtes
    }
    return () => { live = false; };
  }, []);

  const initials = (u.name || '').trim().split(/\s+/).map(w => w[0]).slice(0, 2).join('').toUpperCase() || 'LC';
  const empty = <span style={{ color: 'var(--gray-3)', fontStyle: 'italic', fontWeight: 400 }}>Non renseigné</span>;
  const rows = [
    { l: 'Nom', v: u.name },
    { l: 'Email', v: u.email },
    { l: 'Téléphone', v: lvPhoneFr(u.phone) },
  ];
  return (
    <div className="lc-profile-card">
      <div className="lc-profile-head">
        <div className="lc-profile-avatar">{initials}</div>
        <div style={{ flex: 1 }}>
          <div className="lc-profile-name">{u.name || 'Mon compte'}</div>
          <div className="lc-profile-mail">{lvPhoneFr(u.phone) || u.email || 'Compte Le Cayenne'}</div>
        </div>
      </div>
      <div>
        {rows.map((r, i) => (
          <div key={i} className="lc-profile-row">
            <div>
              <div className="lc-profile-row-lbl">{r.l}</div>
              <div className="lc-profile-row-val">{r.v || empty}</div>
            </div>
          </div>
        ))}
        <div style={{ marginTop: 10, fontSize: 11.5, color: 'var(--gray-3)', lineHeight: 1.5 }}>
          Ton compte est identifié par ton numéro de téléphone. La modification du profil arrive bientôt — en attendant, demande en caisse.
        </div>
      </div>
    </div>
  );
}

// [GOAL-SYNC 2026-07-08] Préférences persistées en LOCAL (localStorage) — plus de toggles
// « démo » perdus à chaque rechargement. Aucun backend de notifications en V1.
const LV_NOTIF_KEY = 'lecayenne.notifPrefs';
function NotificationSettings() {
  const [s, setS] = lvS(() => {
    try {
      const saved = JSON.parse(localStorage.getItem(LV_NOTIF_KEY) || 'null');
      if (saved && typeof saved === 'object') return { orders: true, points: true, news: false, promo: true, sms: true, ...saved };
    } catch (e) {}
    return { orders: true, points: true, news: false, promo: true, sms: true };
  });
  const toggle = (k) => setS(p => {
    const next = { ...p, [k]: !p[k] };
    try { localStorage.setItem(LV_NOTIF_KEY, JSON.stringify(next)); } catch (e) {}
    return next;
  });
  const rows = [
    { k: 'orders', l: 'Statut commande',     d: 'Notifs quand ta commande est prête' },
    { k: 'points', l: 'Points gagnés',        d: 'Confirmation à chaque commande' },
    { k: 'news',   l: 'Nouveautés menu',      d: 'Quand on lance un nouveau plat' },
    { k: 'promo',  l: 'Promos & événements',  d: 'Codes promo, défis hebdo' },
    { k: 'sms',    l: 'SMS de retrait',       d: 'Plus rapide que les push' },
  ];
  return (
    <div className="lc-profile-card">
      <h3 style={{ margin: '0 0 14px', fontFamily: 'var(--font-display)', fontSize: 22, textTransform: 'uppercase', letterSpacing: '-0.005em' }}>Notifications</h3>
      {rows.map(r => (
        <div key={r.k} className="lc-profile-row">
          <div style={{ flex: 1 }}>
            <div className="lc-profile-row-lbl">{r.l}</div>
            <div style={{ fontSize: 12, color: 'var(--gray-3)', marginTop: 4 }}>{r.d}</div>
          </div>
          {/* [WADV-1 heal 2026-06-10] self-closing toggle had NO accessible name (button-name CRITICAL) — SR announced 5 anonymous buttons. */}
          <button className={'lc-toggle' + (s[r.k]?' on':'')} onClick={()=>toggle(r.k)} aria-pressed={s[r.k]} aria-label={r.l + (s[r.k] ? ' — activé' : ' — désactivé')}/>
        </div>
      ))}
    </div>
  );
}

// [GOAL-SYNC 2026-07-08] Fini la « Visa ····4242 » fictive : aucun backend de cartes n'existe
// et le paiement en ligne est OFF (flag feature-online-card). État vide honnête.
function SavedCards() {
  return (
    <div className="lc-profile-card">
      <h3 style={{ margin: '0 0 14px', fontFamily: 'var(--font-display)', fontSize: 22, textTransform: 'uppercase', letterSpacing: '-0.005em' }}>Cartes enregistrées</h3>
      <div style={{ padding: '18px 4px', textAlign: 'center' }}>
        <div style={{ fontSize: 28, lineHeight: 1, marginBottom: 10 }} aria-hidden="true">💳</div>
        <div style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--ink)' }}>Aucune carte enregistrée</div>
        <div style={{ marginTop: 6, fontSize: 12, color: 'var(--gray-3)', lineHeight: 1.5 }}>Le paiement en ligne arrive bientôt. En attendant, tu règles au comptoir (CB acceptée).</div>
      </div>
    </div>
  );
}

function AccountDangerZone({ onLogout }) {
  // [GOAL-SYNC 2026-07-08] « Se déconnecter » était un no-op (screens.jsx passe onLogout={()=>{}}).
  // Câblage robuste local : purge du token (window.LC.api.logout) + callback parent + retour accueil
  // (reload → l'app reboote non-authentifiée sur la home). Fonctionne même si le parent reste no-op.
  const doLogout = () => {
    try { if (window.LC && window.LC.api && window.LC.api.logout) window.LC.api.logout(); } catch (e) {}
    if (typeof onLogout === 'function') { try { onLogout(); } catch (e) {} }
    try { window.location.reload(); } catch (e) {}
  };
  return (
    <div className="lc-profile-card" style={{ background: 'rgba(215,38,56,0.04)', border: '1px solid rgba(215,38,56,0.12)' }}>
      <h3 style={{ margin: '0 0 14px', fontFamily: 'var(--font-display)', fontSize: 22, textTransform: 'uppercase', letterSpacing: '-0.005em', color: 'var(--red)' }}>Zone dangereuse</h3>
      <button onClick={doLogout} style={{ width: '100%', background: 'transparent', border: '1.5px solid var(--red)', color: 'var(--red-text)', padding: '14px', borderRadius: 12, fontSize: 13, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', cursor: 'pointer', marginBottom: 10 }}>Se déconnecter</button>
      {/* [GOAL-SYNC 2026-07-08] Bouton « Supprimer mon compte » inerte RETIRÉ (RGPD : un bouton
          de suppression sans effet est pire qu'absent). Info honnête à la place. */}
      <div style={{ fontSize: 11, color: 'var(--gray-4)', textAlign: 'center', lineHeight: 1.5 }}>Pour supprimer ton compte, demande en caisse ou appelle le restaurant.</div>
    </div>
  );
}

function LoyaltyProfileTab({ onLogout }) {
  return (
    <div className="lc-profile-grid">
      <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
        <ProfileEditor/>
        {/* [GOAL-SYNC 2026-07-08] PreferencesCard RETIRÉE : allergènes « Gluten, Lactose »,
            cuisson « À point » et sauce préférée étaient des valeurs FICTIVES affichées à un
            vrai client (trompeur, boutons sans handler). À recâbler quand un backend existera. */}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
        <NotificationSettings/>
        <SavedCards/>
        <AccountDangerZone onLogout={onLogout}/>
      </div>
    </div>
  );
}

window.LoyaltyProfileTab = LoyaltyProfileTab;
