// Faire-part Ariel & Eden — composant principal

const { useState, useEffect, useRef, useMemo, createContext, useContext } = React;

// ===== Internationalisation FR / HE =====
const LOCALES = {
  fr: {
    'hero.saveTheDate': 'Save the Date',
    'hero.names.left': 'Ariel',
    'hero.names.right': 'Eden',
    'hero.subtitle': 'se marient le',
    'hero.date': '07 · 06 · 2026',
    'hero.cta': 'Voir la carte',
    'cd.days': 'jours',
    'cd.hours': 'heures',
    'cd.minutes': 'minutes',
    'cd.seconds': 'secondes',
    'houppa.title': 'Houppa et soirée',
    'houppa.parents.haddad': 'M. & Mme Mikael Haddad',
    'houppa.parents.bedouk': 'M. & Mme Nicolas Bedouk',
    'houppa.gm.left': 'Mme Annie Journo',
    'houppa.gm.right': 'Mme Sylvia Hazan',
    'houppa.gp.left': 'M. & Mme Freddy Haddad',
    'houppa.gp.right': 'M. Gérard Bedouk',
    'houppa.intro1': 'Remercient ',
    'houppa.intro.hachem': 'Hachem',
    'houppa.intro2': " d'avoir la joie de vous convier au mariage de leurs enfants et petits-enfants,",
    'houppa.couple.left': 'Ariel',
    'houppa.couple.right': 'Eden',
    'houppa.invite0': "et vous prient d'assister",
    'houppa.invite1': 'à la ',
    'houppa.invite.houppa': 'Houppa',
    'houppa.invite2': ' qui aura lieu le ',
    'houppa.date': '7 juin 2026 — 22 Sivan 5786.',
    'houppa.invite3': "Ainsi qu'à la réception qui suivra.",
    'houppa.venue': 'Salle Arya — Shoham, Israël',
    'houppa.schedule': "Kabbalat Panim à 17h30, suivi de la Houppa à 18h45",
    'houppa.memory.title': 'Une pensée pour',
    'houppa.memory.list': 'Mme Michelle Despax · M. Freddy Hazan<br>M. Richard Journo',
    'plan.eyebrow': 'Itinéraire',
    'plan.title': 'Comment venir',
    'plan.shuttle.title': 'Navette',
    'plan.shuttle.text': 'Départ · Jérusalem',
    'plan.address.title': 'Adresse',
    'plan.address.text': 'Arya, Shoham',
    'plan.waze': 'Ouvrir dans Waze',
    'rsvp.eyebrow': 'Confirmation',
    'rsvp.title': 'Réponse',
    'rsvp.deadline.before': 'Merci de confirmer votre présence avant le ',
    'rsvp.deadline.date': '15 mai 2026',
    'rsvp.deadline.after': '.',
    'rsvp.field.firstName': 'Prénom',
    'rsvp.field.firstName.placeholder': 'Votre prénom',
    'rsvp.field.lastName': 'Nom',
    'rsvp.field.lastName.placeholder': 'Votre nom',
    'rsvp.field.count': 'Nombre',
    'rsvp.field.attend': 'Présence',
    'rsvp.attend.yes': 'Oui',
    'rsvp.attend.no': 'Non',
    'rsvp.field.shuttle': 'Navette',
    'rsvp.field.message': 'Petit mot',
    'rsvp.field.message.placeholder': 'Un mot pour les mariés…',
    'rsvp.submit': 'Envoyer',
    'rsvp.submitting': 'Envoi…',
    'rsvp.error': "Erreur d'envoi. Réessaie ou contacte-nous.",
    'rsvp.thanks.title': 'Merci',
    'rsvp.thanks.you': 'cher invité',
    'rsvp.thanks.text': 'Nous avons hâte de partager ce moment avec vous.',
    'footer.date': '07 · 06 · 2026 — Shoham',
    'footer.signature': 'Réalisé par Hillel Amzallag',
    'lang.toggle': 'עברית',
  },
  he: {
    'hero.saveTheDate': 'שמרו את התאריך',
    'hero.names.left': 'עדן',
    'hero.names.right': 'אריאל',
    'hero.subtitle': 'מתחתנים בתאריך',
    'hero.date': '07 · 06 · 2026',
    'hero.cta': 'הצג את ההזמנה',
    'cd.days': 'ימים',
    'cd.hours': 'שעות',
    'cd.minutes': 'דקות',
    'cd.seconds': 'שניות',
    'houppa.title': '',
    'houppa.parents.haddad': "מר וגב' מיכאל חדד",
    'houppa.parents.bedouk': "מר וגב' ניקולא בדוק",
    'houppa.gm.left': "גב' אני ז׳ורנו",
    'houppa.gm.right': "גב' סילביה חזן",
    'houppa.gp.left': "מר וגב' פרדי חדד",
    'houppa.gp.right': "מר ג׳ראר בדוק",
    'houppa.intro1': 'מודים ל',
    'houppa.intro.hachem': 'הקדוש ברוך הוא',
    'houppa.intro2': ' על הזכות להזמין אתכם לחתונת ילדיהם ונכדיהם,',
    'houppa.couple.left': 'עדן',
    'houppa.couple.right': 'אריאל',
    'houppa.invite0': 'ומתכבדים להזמינכם להשתתף',
    'houppa.invite1': 'ל',
    'houppa.invite.houppa': 'חופה',
    'houppa.invite2': ' שתתקיים בתאריך ',
    'houppa.date': "כ״ב סיון תשפ״ו — 7 ביוני 2026.",
    'houppa.invite3': '',
    'houppa.venue': 'אולם אריה — שוהם, ישראל',
    'houppa.schedule': 'קבלת פנים ב־17:30 ולאחריה החופה ב־18:45',
    'houppa.memory.title': 'לזכרם',
    'houppa.memory.list': "גב' מישל דספקס · מר פרדי חזן<br>מר ריצ׳רד ז׳ורנו",
    'plan.eyebrow': 'הגעה',
    'plan.title': 'איך מגיעים',
    'plan.shuttle.title': 'הסעה',
    'plan.shuttle.text': 'יציאה · ירושלים',
    'plan.address.title': 'כתובת',
    'plan.address.text': 'אריה, שוהם',
    'plan.waze': 'פתח ב־Waze',
    'rsvp.eyebrow': 'אישור הגעה',
    'rsvp.title': 'תשובה',
    'rsvp.deadline.before': 'נא לאשר הגעה עד ',
    'rsvp.deadline.date': '15 במאי 2026',
    'rsvp.deadline.after': '.',
    'rsvp.field.firstName': 'שם פרטי',
    'rsvp.field.firstName.placeholder': 'השם הפרטי שלך',
    'rsvp.field.lastName': 'שם משפחה',
    'rsvp.field.lastName.placeholder': 'שם המשפחה שלך',
    'rsvp.field.count': 'מספר אורחים',
    'rsvp.field.attend': 'הגעה',
    'rsvp.attend.yes': 'כן',
    'rsvp.attend.no': 'לא',
    'rsvp.field.shuttle': 'הסעה',
    'rsvp.field.message': 'הודעה קצרה',
    'rsvp.field.message.placeholder': 'מילה טובה לזוג…',
    'rsvp.submit': 'שליחה',
    'rsvp.submitting': 'שולח…',
    'rsvp.error': 'שגיאה בשליחה. נסה שוב או צור קשר.',
    'rsvp.thanks.title': 'תודה',
    'rsvp.thanks.you': 'אורח יקר',
    'rsvp.thanks.text': 'נשמח לחגוג איתכם את הרגע הזה.',
    'footer.date': '07 · 06 · 2026 — שוהם',
    'footer.signature': 'נוצר על ידי הילל אמזלג',
    'lang.toggle': 'Français',
  },
};

const LangContext = createContext({ lang: 'fr', setLang: () => {} });
const useT = () => {
  const { lang } = useContext(LangContext);
  return (key) => {
    const v = LOCALES[lang]?.[key];
    if (v !== undefined) return v;
    const fr = LOCALES.fr[key];
    return fr !== undefined ? fr : key;
  };
};
const useLang = () => useContext(LangContext);

// ===== B"H — pastille religieuse en haut de chaque section =====
const Bsd = () => (
  <div className="bsd" aria-hidden="true">ב״ה</div>
);

// ===== Toggle de langue FR / HE =====
const LangToggle = () => {
  const { lang, setLang } = useLang();
  const t = useT();
  return (
    <button
      className="lang-toggle"
      onClick={() => setLang(lang === 'fr' ? 'he' : 'fr')}
      aria-label="Changer de langue"
    >
      <span>{t('lang.toggle')}</span>
    </button>
  );
};

// ===== Texte hébreu en arc (קול ששון וקול שמחה קול חתן וקול כלה) =====
// Astuce cross-browser (Chrome + Safari iOS) : on pré-inverse la string en Unicode
// et on force unicode-bidi:bidi-override + direction:ltr pour empêcher le browser de re-inverser.
// Avec le path L→R, les glyphes sont head-up et le résultat lu R→L est dans le bon sens.
const ARC_TEXT_HE = 'קול ששון וקול שמחה קול חתן וקול כלה';
const ARC_TEXT_VISUAL = ARC_TEXT_HE.split('').reverse().join('');

const ArcText = () => (
  <div className="arc-text" aria-hidden="true">
    <svg viewBox="0 0 600 140" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
      <defs>
        <linearGradient id="arc-gold" x1="0%" y1="0%" x2="100%" y2="0%">
          <stop offset="0%" stopColor="#d4af6a" stopOpacity="0" />
          <stop offset="20%" stopColor="#b89249" stopOpacity="0.95" />
          <stop offset="50%" stopColor="#8c6b32" stopOpacity="1" />
          <stop offset="80%" stopColor="#b89249" stopOpacity="0.95" />
          <stop offset="100%" stopColor="#d4af6a" stopOpacity="0" />
        </linearGradient>
        <path id="arc-path" d="M 40 130 Q 300 -10 560 130" fill="none" />
      </defs>
      <text fill="url(#arc-gold)" fontFamily="'David Libre', 'Frank Ruhl Libre', serif" fontSize="32" fontWeight="500" letterSpacing="2" style={{unicodeBidi: 'bidi-override', direction: 'ltr'}}>
        <textPath href="#arc-path" startOffset="50%" textAnchor="middle">
          {ARC_TEXT_VISUAL}
        </textPath>
      </text>
    </svg>
  </div>
);

// ===== Compte à rebours =====
const useCountdown = (target) => {
  const [now, setNow] = useState(Date.now());
  useEffect(() => {
    const i = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(i);
  }, []);
  const diff = Math.max(0, target - now);
  const days = Math.floor(diff / 86400000);
  const hours = Math.floor((diff % 86400000) / 3600000);
  const minutes = Math.floor((diff % 3600000) / 60000);
  const seconds = Math.floor((diff % 60000) / 1000);
  return { days, hours, minutes, seconds };
};

// ===== Pétales qui tombent =====
const FallingPetals = ({ count = 18, palette }) => {
  const petals = useMemo(
    () =>
      Array.from({ length: count }).map((_, i) => ({
        id: i,
        left: Math.random() * 100,
        delay: Math.random() * 12,
        duration: 14 + Math.random() * 10,
        size: 10 + Math.random() * 10,
        hue: ['blush', 'pink', 'gold'][i % 3],
        sway: Math.random() * 60 - 30,
        rotate: Math.random() * 720 - 360,
      })),
    [count]
  );
  return (
    <div className="petals-layer" aria-hidden="true">
      {petals.map((p) => (
        <div
          key={p.id}
          className="petal-fall"
          style={{
            left: `${p.left}%`,
            animationDelay: `${p.delay}s`,
            animationDuration: `${p.duration}s`,
            ['--sway']: `${p.sway}px`,
            ['--rot']: `${p.rotate}deg`,
          }}
        >
          <window.Petal size={p.size} hue={p.hue} />
        </div>
      ))}
    </div>
  );
};

// ===== Compte à rebours UI =====
const Countdown = ({ target }) => {
  const { days, hours, minutes, seconds } = useCountdown(target);
  const t = useT();
  const items = [
    { v: days, lbl: t('cd.days') },
    { v: hours, lbl: t('cd.hours') },
    { v: minutes, lbl: t('cd.minutes') },
    { v: seconds, lbl: t('cd.seconds') },
  ];
  return (
    <div className="countdown">
      {items.map((it, i) => (
        <React.Fragment key={i}>
          <div className="cd-cell">
            <div className="cd-num">{String(it.v).padStart(2, '0')}</div>
            <div className="cd-lbl">
              <span>{it.lbl}</span>
            </div>
          </div>
          {i < items.length - 1 && <div className="cd-sep">·</div>}
        </React.Fragment>
      ))}
    </div>
  );
};

// ===== Reveal on scroll =====
const useReveal = () => {
  const ref = useRef(null);
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const obs = new IntersectionObserver(
      ([e]) => { if (e.isIntersecting) setVisible(true); },
      { threshold: 0.18 }
    );
    obs.observe(el);
    return () => obs.disconnect();
  }, []);
  return [ref, visible];
};

// ===== Section: Hero =====
const Hero = ({ targetDate, onEnter, density }) => {
  const t = useT();
  return (
    <section className="hero" data-screen-label="01 Hero">
      <Bsd />
      {/* Bouquets aquarelle — bas et haut (gérés via background-image dans .hero) */}

      <div className="hero-inner">
        <div className="hero-names">
          <div className="name-row">
            <div className="name-fr">{t('hero.names.left')}</div>
            <div className="amp">
              <svg viewBox="0 0 80 80" width="84" height="84">
                <defs>
                  <linearGradient id="amp-gold" x1="0%" y1="0%" x2="100%" y2="100%">
                    <stop offset="0%" stopColor="#d4af6a" />
                    <stop offset="100%" stopColor="#9a7a3a" />
                  </linearGradient>
                </defs>
                <text x="40" y="60" textAnchor="middle" fontSize="68" fontFamily="'Great Vibes', cursive" fill="url(#amp-gold)">&amp;</text>
              </svg>
            </div>
            <div className="name-fr">{t('hero.names.right')}</div>
          </div>
        </div>

        <div className="hero-marie-line">
          <span className="hero-sub-inline">{t('hero.subtitle')}</span>
          <span className="hero-date-inline">{t('hero.date')}</span>
        </div>

        <Countdown target={targetDate} />

        <button className="btn-primary" onClick={onEnter}>
          <span className="btn-line">{t('hero.cta')}</span>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <path d="M6 9l6 6 6-6" />
          </svg>
        </button>
      </div>
    </section>
  );
};

// ===== Section: Houppa et soirée =====
const MotMaries = ({ density }) => {
  const [ref, visible] = useReveal();
  const t = useT();
  return (
    <section ref={ref} className={`section mot houppa ${visible ? 'is-visible' : ''}`} data-screen-label="02 Houppa et soirée">
      <Bsd />
      <div className="section-inner">
        <ArcText />
        <h2 className="script-title">{t('houppa.title')}</h2>

        <window.FloralDivider width={200} />

        <div className="parents-grid">
          <p className="parent-l">{t('houppa.parents.bedouk')}</p>
          <p className="parent-r">{t('houppa.parents.haddad')}</p>
          <p className="parent-l">{t('houppa.gm.right')}</p>
          <p className="parent-r">{t('houppa.gm.left')}</p>
          <p className="parent-l">{t('houppa.gp.right')}</p>
          <p className="parent-r">{t('houppa.gp.left')}</p>
        </div>

        <p className="invite-prose">
          {t('houppa.intro1')}<span className="gold-em">{t('houppa.intro.hachem')}</span>{t('houppa.intro2')}
        </p>

        <div className="couple-block">
          <div className="couple-names">
            <span className="couple-name">{t('houppa.couple.left')}</span>
            <span className="couple-amp">&amp;</span>
            <span className="couple-name">{t('houppa.couple.right')}</span>
          </div>
        </div>

        <p className="invite-prose">{t('houppa.invite0')}</p>

        <p className="invite-prose">
          {t('houppa.invite1')}<span className="gold-em">{t('houppa.invite.houppa')}</span>{t('houppa.invite2')}<br /><span className="gold-em">{t('houppa.date')}</span>
        </p>

        <p className="invite-prose"><strong>{t('houppa.schedule')}</strong></p>

        <p className="invite-prose">{t('houppa.invite3')}</p>

        <p className="invite-he">{t('houppa.venue')}</p>

        <div className="memory-block">
          <div className="memory-title">{t('houppa.memory.title')}</div>
          <div className="memory-list" dangerouslySetInnerHTML={{ __html: t('houppa.memory.list') }} />
        </div>
      </div>
    </section>
  );
};

// ===== Section: RSVP =====
// URL du Web App Apps Script (à coller après publication, voir apps-script/SETUP.md)
const RSVP_ENDPOINT = window.RSVP_ENDPOINT || '';

const RSVP = () => {
  const [ref, visible] = useReveal();
  const t = useT();
  const [form, setForm] = useState({ firstName: '', lastName: '', count: 1, attend: 'yes', shuttle: 'no', message: '' });
  const [sent, setSent] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState('');
  const [pulse, setPulse] = useState('');
  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));
  const pickPill = (groupKey, val) => {
    set(groupKey, val);
    const id = `${groupKey}-${val}`;
    setPulse(id);
    setTimeout(() => setPulse((p) => (p === id ? '' : p)), 420);
  };

  const yesNo = [
    { v: 'yes', label: t('rsvp.attend.yes') },
    { v: 'no', label: t('rsvp.attend.no') },
  ];

  const submit = async (e) => {
    e.preventDefault();
    setError('');
    setSubmitting(true);
    try {
      if (RSVP_ENDPOINT) {
        // Apps Script Web App accepte les POST en text/plain (pas de preflight CORS)
        await fetch(RSVP_ENDPOINT, {
          method: 'POST',
          mode: 'no-cors',
          headers: { 'Content-Type': 'text/plain;charset=utf-8' },
          body: JSON.stringify(form),
        });
      }
      setSent(true);
    } catch (err) {
      setError(t('rsvp.error'));
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <section ref={ref} className={`section rsvp ${visible ? 'is-visible' : ''}`} data-screen-label="04 RSVP">
      <Bsd />
      <div className="section-inner">
        <div className="eyebrow">
          <span>{t('rsvp.eyebrow')}</span>
        </div>
        <h2 className="script-title">{t('rsvp.title')}</h2>

        <window.FloralDivider width={200} />

        <p className="prose center">
          {t('rsvp.deadline.before')}<strong>{t('rsvp.deadline.date')}</strong>{t('rsvp.deadline.after')}
        </p>

        {!sent ? (
          <form className="rsvp-form" onSubmit={submit}>
            <div className="field-row">
              <label className="field">
                <span>{t('rsvp.field.firstName')}</span>
                <input
                  type="text"
                  value={form.firstName}
                  onChange={(e) => set('firstName', e.target.value)}
                  required
                  placeholder={t('rsvp.field.firstName.placeholder')}
                />
              </label>
              <label className="field">
                <span>{t('rsvp.field.lastName')}</span>
                <input
                  type="text"
                  value={form.lastName}
                  onChange={(e) => set('lastName', e.target.value)}
                  required
                  placeholder={t('rsvp.field.lastName.placeholder')}
                />
              </label>
            </div>

            <div className="field-row">
              <label className="field">
                <span>{t('rsvp.field.count')}</span>
                <input
                  type="number"
                  min="1"
                  max="10"
                  value={form.count}
                  onChange={(e) => set('count', e.target.value)}
                />
              </label>

              <div className="field">
                <span>{t('rsvp.field.attend')}</span>
                <div className="radio-row">
                  {yesNo.map((o) => (
                    <button
                      key={o.v}
                      type="button"
                      className={`radio-pill ${form.attend === o.v ? 'is-on' : ''} ${pulse === `attend-${o.v}` ? 'is-pulse' : ''}`}
                      onClick={() => pickPill('attend', o.v)}
                    >
                      <span>{o.label}</span>
                    </button>
                  ))}
                </div>
              </div>
            </div>

            {form.attend === 'yes' && (
              <div className="field">
                <span>{t('rsvp.field.shuttle')}</span>
                <div className="radio-row">
                  {yesNo.map((o) => (
                    <button
                      key={o.v}
                      type="button"
                      className={`radio-pill ${form.shuttle === o.v ? 'is-on' : ''} ${pulse === `shuttle-${o.v}` ? 'is-pulse' : ''}`}
                      onClick={() => pickPill('shuttle', o.v)}
                    >
                      <span>{o.label}</span>
                    </button>
                  ))}
                </div>
              </div>
            )}

            <label className="field">
              <span>{t('rsvp.field.message')}</span>
              <textarea
                rows="3"
                value={form.message}
                onChange={(e) => set('message', e.target.value)}
                placeholder={t('rsvp.field.message.placeholder')}
              />
            </label>

            <button type="submit" className="btn-primary submit" disabled={submitting}>
              <span>{submitting ? t('rsvp.submitting') : t('rsvp.submit')}</span>
            </button>

            {error && <div className="rsvp-error">{error}</div>}
          </form>
        ) : (
          <div className="thanks">
            <img src="assets/gold-rose.png" alt="" style={{width: 120, height: 120, objectFit: 'contain'}} />
            <h3>{t('rsvp.thanks.title')}, {form.firstName || t('rsvp.thanks.you')} !</h3>
            <p>{t('rsvp.thanks.text')}</p>
          </div>
        )}
      </div>
    </section>
  );
};

// ===== Section: Plan / Itinéraire =====
const PlanSection = () => {
  const [ref, visible] = useReveal();
  const t = useT();
  return (
    <section ref={ref} className={`section plan ${visible ? 'is-visible' : ''}`} data-screen-label="05 Plan">
      <Bsd />
      <div className="section-inner">
        <div className="eyebrow">
          <span>{t('plan.eyebrow')}</span>
        </div>
        <h2 className="script-title">{t('plan.title')}</h2>

        <window.FloralDivider width={200} />

        <div className="map-wrap">
          {/* SVG placeholder map illustrative */}
          <svg viewBox="0 0 600 320" className="map-svg" xmlns="http://www.w3.org/2000/svg">
            <defs>
              <linearGradient id="map-bg" x1="0%" y1="0%" x2="100%" y2="100%">
                <stop offset="0%" stopColor="#f8f1e8" />
                <stop offset="100%" stopColor="#efe4d5" />
              </linearGradient>
              <pattern id="map-dots" patternUnits="userSpaceOnUse" width="20" height="20">
                <circle cx="10" cy="10" r="0.6" fill="#c9a961" opacity="0.3" />
              </pattern>
            </defs>
            <rect width="600" height="320" fill="url(#map-bg)" />
            <rect width="600" height="320" fill="url(#map-dots)" />
            {/* Routes */}
            <path d="M 0 180 Q 200 120 400 200 T 600 220" stroke="#c9a961" strokeWidth="2" fill="none" opacity="0.55" strokeDasharray="6 4" />
            <path d="M 100 0 Q 180 100 220 180 T 320 320" stroke="#c9a961" strokeWidth="1.5" fill="none" opacity="0.4" strokeDasharray="4 3" />
            <path d="M 600 80 Q 480 140 380 200" stroke="#c9a961" strokeWidth="1.2" fill="none" opacity="0.35" strokeDasharray="3 3" />

            {/* Labels villes */}
            <text x="80" y="80" fontSize="11" fontFamily="'Cormorant Garamond', serif" fill="#9a7a3a" opacity="0.7" fontStyle="italic">Tel Aviv</text>
            <text x="500" y="60" fontSize="11" fontFamily="'Cormorant Garamond', serif" fill="#9a7a3a" opacity="0.7" fontStyle="italic">Jerusalem</text>
            <text x="50" y="280" fontSize="11" fontFamily="'Cormorant Garamond', serif" fill="#9a7a3a" opacity="0.7" fontStyle="italic">Modi'in</text>

            {/* Pin Shoham */}
            <g transform="translate(310 195)">
              <circle r="22" fill="#e8b4bc" opacity="0.4">
                <animate attributeName="r" values="22;32;22" dur="3s" repeatCount="indefinite" />
                <animate attributeName="opacity" values="0.4;0.1;0.4" dur="3s" repeatCount="indefinite" />
              </circle>
              <path d="M 0 -18 C -10 -18 -14 -10 -14 -4 C -14 6 0 18 0 18 C 0 18 14 6 14 -4 C 14 -10 10 -18 0 -18 Z" fill="#b9606e" />
              <circle cx="0" cy="-6" r="4" fill="#faf6f1" />
              <text x="0" y="40" textAnchor="middle" fontSize="14" fontFamily="'Cormorant Garamond', serif" fontStyle="italic" fill="#7e4651">Shoham</text>
              <text x="0" y="56" textAnchor="middle" fontSize="11" fontFamily="'Cormorant Garamond', serif" fill="#9a7a3a">Arya</text>
            </g>
          </svg>
        </div>

        <div className="plan-grid plan-grid-2">
          <div className="plan-card">
            <div className="pc-icon">
              <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="#9a7a3a" strokeWidth="1.5">
                <rect x="4" y="3" width="16" height="16" rx="2" />
                <path d="M4 11h16M9 19v2M15 19v2" /><circle cx="8" cy="15" r="1" /><circle cx="16" cy="15" r="1" />
              </svg>
            </div>
            <div className="pc-title">{t('plan.shuttle.title')}</div>
            <div className="pc-text">{t('plan.shuttle.text')}</div>
          </div>

          <div className="plan-card">
            <div className="pc-icon">
              <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="#9a7a3a" strokeWidth="1.5">
                <path d="M12 2C8 2 5 5 5 9c0 5 7 13 7 13s7-8 7-13c0-4-3-7-7-7z" /><circle cx="12" cy="9" r="2.5" />
              </svg>
            </div>
            <div className="pc-title">{t('plan.address.title')}</div>
            <div className="pc-text">{t('plan.address.text')}</div>
          </div>
        </div>

        <a className="btn-secondary" href="https://waze.com/ul?q=Arya+Shoham+Israel&navigate=yes" target="_blank" rel="noopener">
          <span>{t('plan.waze')}</span>
        </a>
      </div>
    </section>
  );
};

// ===== Footer =====
const Footer = () => {
  const t = useT();
  return (
    <footer className="footer">
      <Bsd />
      <window.FloralDivider width={240} opacity={0.6} />
      <div className="foot-names">
        <span>{t('houppa.couple.left')} &amp; {t('houppa.couple.right')}</span>
      </div>
      <div className="foot-date">{t('footer.date')}</div>
      <div className="foot-heart">
        <svg viewBox="0 0 24 24" width="14" height="14" fill="#c47670">
          <path d="M12 21s-7-4.5-9.5-9C1 9 2.5 5 6.5 5c2 0 3.5 1 5.5 3 2-2 3.5-3 5.5-3 4 0 5.5 4 4 7-2.5 4.5-9.5 9-9.5 9z" />
        </svg>
      </div>
      <div className="foot-credit">
        <span>{t('footer.signature')}</span>
        <a href="tel:+972532569935" className="foot-credit-tel">+972 53 256 9935</a>
      </div>
    </footer>
  );
};

// ===== App =====
const App = () => {
  const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
    "palette": "blush",
    "density": "medium",
    "petals": true,
    "scriptFont": "Pinyon Script",
    "petalCount": 10
  }/*EDITMODE-END*/;

  const [tweaks, setTweak] = window.useTweaks(TWEAK_DEFAULTS);
  const [revealed, setRevealed] = useState(false);
  const [lang, setLang] = useState('fr');
  const cardRef = useRef(null);
  const audioRef = useRef(null);
  const target = new Date('2026-06-07T19:00:00+03:00').getTime();

  // Synchronise <html dir> avec la langue choisie (RTL pour HE)
  useEffect(() => {
    document.documentElement.lang = lang;
    document.documentElement.dir = lang === 'he' ? 'rtl' : 'ltr';
  }, [lang]);

  const onEnter = () => {
    // Démarre la musique à 19s (geste utilisateur → autoplay autorisé)
    const audio = audioRef.current;
    if (audio) {
      // play() en premier (geste utilisateur OK), puis seek à 41s une fois la lecture lancée
      audio.play().then(() => {
        audio.currentTime = 41;
      }).catch(() => {});
    }
    setRevealed(true);
    setTimeout(() => {
      document.querySelector('.section.houppa')?.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }, 80);
  };

  // Apply palette via CSS custom props on root
  useEffect(() => {
    const palettes = {
      blush: {
        '--ivory': '#ffffff',
        '--ivory-2': '#f7f1e6',
        '--rose': '#e8b4bc',
        '--rose-deep': '#c47670',
        '--gold': '#b89249',
        '--gold-soft': '#d4af6a',
        '--ink': '#3d2b2e',
        '--mute': '#7c5b5e',
      },
      blanc: {
        '--ivory': '#fdfaf6',
        '--ivory-2': '#f5edde',
        '--rose': '#f0c2bc',
        '--rose-deep': '#c47e88',
        '--gold': '#c9a961',
        '--gold-soft': '#e0c890',
        '--ink': '#3a2c2e',
        '--mute': '#8b6e70',
      },
      sauge: {
        '--ivory': '#f7f3ec',
        '--ivory-2': '#ebe5d6',
        '--rose': '#e6acb4',
        '--rose-deep': '#b9606e',
        '--gold': '#a89070',
        '--gold-soft': '#c4a886',
        '--ink': '#2f3a2c',
        '--mute': '#6a7560',
      },
    };
    const p = palettes[tweaks.palette] || palettes.blush;
    Object.entries(p).forEach(([k, v]) => document.documentElement.style.setProperty(k, v));
    document.documentElement.style.setProperty('--script', `'${tweaks.scriptFont || 'Great Vibes'}', cursive`);
  }, [tweaks.palette, tweaks.scriptFont]);

  return (
    <LangContext.Provider value={{ lang, setLang }}>
    <div className="app" ref={cardRef}>
      {tweaks.petals && <FallingPetals count={tweaks.petalCount} palette={tweaks.palette} />}

      <LangToggle />
      <audio ref={audioRef} src="assets/song-ariel-eden.mp3" preload="auto" />

      <Hero targetDate={target} onEnter={onEnter} density={tweaks.density} />
      <div className={`revealed-content ${revealed ? 'is-revealed' : ''}`} aria-hidden={!revealed}>
        <MotMaries density={tweaks.density} />
        <PlanSection />
        <RSVP />
        <Footer />
      </div>

      {/* Tweaks panel */}
      <window.TweaksPanel title="Tweaks">
        <window.TweakSection title="Palette">
          <window.TweakSelect
            label="Couleurs"
            value={tweaks.palette}
            onChange={(v) => setTweak('palette', v)}
            options={[
              { value: 'blush', label: 'Rose poudré + ivoire + or' },
              { value: 'blanc', label: 'Rose pâle + champagne' },
              { value: 'sauge', label: 'Rose + sauge + crème' },
            ]}
          />
        </window.TweakSection>

        <window.TweakSection title="Floral">
          <window.TweakRadio
            label="Densité"
            value={tweaks.density}
            onChange={(v) => setTweak('density', v)}
            options={[
              { value: 'sparse', label: 'Discret' },
              { value: 'medium', label: 'Modéré' },
              { value: 'generous', label: 'Généreux' },
            ]}
          />
          <window.TweakToggle
            label="Pétales qui tombent"
            value={tweaks.petals}
            onChange={(v) => setTweak('petals', v)}
          />
          <window.TweakSlider
            label="Nombre de pétales"
            min={6}
            max={40}
            step={1}
            value={tweaks.petalCount}
            onChange={(v) => setTweak('petalCount', v)}
          />
        </window.TweakSection>

        <window.TweakSection title="Typographie">
          <window.TweakSelect
            label="Calligraphie des noms"
            value={tweaks.scriptFont}
            onChange={(v) => setTweak('scriptFont', v)}
            options={[
              { value: 'Italianno', label: 'Italianno (élégante & fine)' },
              { value: 'Tangerine', label: 'Tangerine (étirée)' },
              { value: 'Mrs Saint Delafield', label: 'Mrs Saint Delafield (manuscrite)' },
              { value: 'Petit Formal Script', label: 'Petit Formal Script (formelle)' },
              { value: 'Great Vibes', label: 'Great Vibes (très fluide)' },
              { value: 'Allura', label: 'Allura (élancée)' },
              { value: 'Pinyon Script', label: 'Pinyon Script (fine)' },
              { value: 'Parisienne', label: 'Parisienne (douce)' },
            ]}
          />
        </window.TweakSection>
      </window.TweaksPanel>
    </div>
    </LangContext.Provider>
  );
};

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
