// app.jsx — Main app composition
const { useState: aUseState, useEffect: aUseEffect, useRef: aUseRef } = React;

function Nav({ t, lang, setLang, theme, setTheme }) {
  const active = useActiveSection(["hero", "heritage", "mission", "voices", "features", "agent", "contrast", "journey", "destinations", "operators", "vision", "faq", "contact"]);
  const scrolled = useScrolled(80);
  const sections = [
    { id: "heritage", label: t.nav.heritage || (lang === "fr" ? "Héritage" : "Heritage") },
    { id: "mission", label: t.nav.mission },
    { id: "features", label: t.nav.features },
    { id: "agent", label: t.nav.agent },
    { id: "journey", label: t.nav.journey },
    { id: "vision", label: t.nav.vision },
    { id: "operators", label: t.nav.operators },
    { id: "contact", label: t.nav.contact },
  ];
  const toggleTheme = () => setTheme(theme === "dark" ? "light" : "dark");
  // État du menu mobile (drawer plein écran depuis le haut). Fermé par
  // défaut, ouvert quand l'utilisateur clique sur le bouton burger qui
  // n'apparaît qu'en dessous de 900px (CSS).
  const [menuOpen, setMenuOpen] = aUseState(false);
  // Ferme le menu dès qu'un lien est cliqué + à chaque changement de
  // section active (utile si l'utilisateur scrolle pendant que c'est ouvert).
  aUseEffect(() => { setMenuOpen(false); }, [active]);
  // Lock du scroll body quand le menu est ouvert
  aUseEffect(() => {
    document.body.style.overflow = menuOpen ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [menuOpen]);

  const themeBtn = (
    <button type="button" className="theme-toggle" onClick={toggleTheme} data-hover aria-label="Toggle theme" title={theme === "dark" ? "Passer au clair" : "Passer au sombre"}>
      <span className="theme-track">
        <span className="theme-thumb" data-theme={theme}>
          {theme === "dark" ? (
            <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>
          ) : (
            <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/></svg>
          )}
        </span>
      </span>
    </button>
  );
  const langBtn = (
    <div className="lang-switch">
      <button type="button" className={lang === "fr" ? "active" : ""} onClick={() => setLang("fr")}>FR</button>
      <button type="button" className={lang === "en" ? "active" : ""} onClick={() => setLang("en")}>EN</button>
    </div>
  );

  return (
    <>
      <div className={`nav ${scrolled ? "scrolled" : ""}`} data-hover>
        <a href="#hero" className="nav-brand" data-hover>
          <img src="assets/logo.png" alt="FasoTravel"/>
          <span className="nav-brand-name">FasoTravel</span>
        </a>
        <div className="nav-links-mid" style={{ display: "flex", gap: 0, padding: "0 4px", borderLeft: "1px solid var(--line)" }}>
          {sections.map(s => (
            <a key={s.id} href={`#${s.id}`} className={`nav-link ${active === s.id ? "active" : ""}`} data-hover>{s.label}</a>
          ))}
        </div>
        <div className="nav-actions">
          {themeBtn}
          {langBtn}
          <button
            type="button"
            className={`nav-burger ${menuOpen ? "open" : ""}`}
            onClick={() => setMenuOpen(o => !o)}
            aria-label={menuOpen ? "Fermer le menu" : "Ouvrir le menu"}
            aria-expanded={menuOpen}
            data-hover
          >
            <span/><span/><span/>
          </button>
        </div>
      </div>

      {/* Drawer mobile — apparaît uniquement < 900px via CSS */}
      <div className={`nav-drawer ${menuOpen ? "open" : ""}`} aria-hidden={!menuOpen}>
        <div className="nav-drawer-inner">
          {sections.map(s => (
            <a
              key={s.id}
              href={`#${s.id}`}
              className={`nav-drawer-link ${active === s.id ? "active" : ""}`}
              onClick={() => setMenuOpen(false)}
            >
              {s.label}
            </a>
          ))}
        </div>
      </div>
      {menuOpen && <div className="nav-drawer-backdrop" onClick={() => setMenuOpen(false)}/>}
    </>
  );
}

function App() {
  const [lang, setLang] = aUseState(() => {
    try { return localStorage.getItem("ft_lang") || "fr"; } catch { return "fr"; }
  });
  const [theme, setTheme] = aUseState(() => {
    try { return localStorage.getItem("ft_theme") || "dark"; } catch { return "dark"; }
  });
  aUseEffect(() => {
    try { localStorage.setItem("ft_lang", lang); } catch {}
    window.FT_T = window.FT_I18N[lang];
  }, [lang]);
  aUseEffect(() => {
    try { localStorage.setItem("ft_theme", theme); } catch {}
    document.documentElement.classList.toggle("light", theme === "light");
  }, [theme]);

  const t = window.FT_I18N[lang];
  window.FT_T = t;
  const progress = useScrollProgress();

  const [notifyOpen, setNotifyOpen] = aUseState(false);
  const [notifyPhone, setNotifyPhone] = aUseState("");
  const [notifySent, setNotifySent] = aUseState(false);

  // Modal Partenaire (transporteurs) — collecte d'infos riches.
  const [partnerOpen, setPartnerOpen] = aUseState(false);
  const [partnerForm, setPartnerForm] = aUseState({
    company: "", contact: "", phone: "", city: "", fleet: "", message: ""
  });
  const [partnerSent, setPartnerSent] = aUseState(false);

  const handleNotify = () => setNotifyOpen(true);
  const handlePartner = () => setPartnerOpen(true);

  // Helpers d'envoi (mock pour l'instant) — POST sera branché quand le
  // backend exposera /waitlist et /partners. En attendant on persiste en
  // localStorage pour ne perdre aucune candidature collectée pendant le
  // pré-lancement, et on ouvre WhatsApp côté utilisateur en option.
  const persistLead = (key, payload) => {
    try {
      const raw = localStorage.getItem(key);
      const arr = raw ? JSON.parse(raw) : [];
      arr.push({ ...payload, ts: new Date().toISOString() });
      localStorage.setItem(key, JSON.stringify(arr));
    } catch (e) { /* ignore */ }
  };

  const submitNotify = (e) => {
    e.preventDefault();
    if (!notifyPhone || notifyPhone.trim().length < 6) return;
    persistLead("ft_waitlist", { phone: notifyPhone.trim(), lang });
    setNotifySent(true);
    setTimeout(() => { setNotifyOpen(false); setNotifySent(false); setNotifyPhone(""); }, 2200);
  };

  const submitPartner = (e) => {
    e.preventDefault();
    const { company, contact, phone, city, fleet, message } = partnerForm;
    if (!company.trim() || !contact.trim() || !phone.trim()) return;
    const text = [
      `🚌 *Candidature Partenaire FasoTravel*`,
      ``,
      `*Société :* ${company.trim()}`,
      `*Contact :* ${contact.trim()}`,
      `*Téléphone :* +226 ${phone.trim()}`,
      city.trim() ? `*Ville :* ${city.trim()}` : null,
      fleet ? `*Flotte :* ${fleet} véhicules` : null,
      message.trim() ? `*Message :* ${message.trim()}` : null,
    ].filter(Boolean).join("\n");
    const waUrl = `https://wa.me/22651591414?text=${encodeURIComponent(text)}`;
    window.open(waUrl, "_blank");
    setPartnerSent(true);
    setTimeout(() => {
      setPartnerOpen(false);
      setPartnerSent(false);
      setPartnerForm({ company: "", contact: "", phone: "", city: "", fleet: "", message: "" });
    }, 2400);
  };

  return (
    <>
      <div className="noise"/>
      <DustParticles/>
      <CustomCursor/>
      <div className="scroll-progress" style={{ width: `${progress}%` }}/>

      <Nav t={t} lang={lang} setLang={setLang} theme={theme} setTheme={setTheme}/>

      <main className="snap-wrap">
        <Hero t={t} onNotify={handleNotify}/>
        <FasoDanfani/>
        <Heritage t={t}/>
        <FasoDanfani/>
        <Mission t={t}/>
        <Voices t={t}/>
        <StatsStrip t={t}/>
        {/* Features porte désormais la démo interactive (MobileDemoFrame
            au centre) — pas de section dédiée séparée pour éviter la
            duplication de cadres téléphone. */}
        <Features t={t} onNotify={handleNotify}/>
        <WhatsAppAgent t={t} lang={lang} onNotify={handleNotify}/>
        <Contrast t={t}/>
        <FasoDanfani/>
        <Journey t={t}/>
        <Destinations t={t}/>
        <Payments t={t}/>
        <Operators t={t} onNotify={handleNotify} onPartner={handlePartner}/>
        <Vision t={t}/>
        <FAQ t={t}/>
        <FinalCTA t={t} onNotify={handleNotify} lang={lang}/>
        <Footer t={t}/>
      </main>

      {/* Modal téléchargement — liens App Store & Google Play */}
      {notifyOpen && (
        <div className="ft-modal-backdrop" onClick={() => setNotifyOpen(false)}>
          <div className="ft-modal" onClick={e => e.stopPropagation()}>
            <button type="button" className="ft-modal-close" onClick={() => setNotifyOpen(false)} data-hover aria-label="Fermer">×</button>
            <div style={{ textAlign: "center" }}>
              <div style={{ display: "inline-block", marginBottom: 16 }}>
                <LogoCoin size={70}/>
              </div>
              <h3 className="ft-modal-title">
                {lang === "fr" ? "Téléchargez FasoTravel" : "Download FasoTravel"}
              </h3>
              <p className="ft-modal-sub">
                {lang === "fr"
                  ? "Disponible gratuitement sur App Store et Google Play."
                  : "Available for free on App Store and Google Play."}
              </p>
              <div style={{ display: "flex", flexDirection: "column", gap: 12, marginTop: 24 }}>
                <a href="#" className="btn btn-primary" data-hover style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 10 }}>
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M17.05 20.28c-.98.95-2.05.8-3.08.35-1.09-.46-2.09-.48-3.24 0-1.44.62-2.2.44-3.06-.35C2.79 15.25 3.51 7.59 9.05 7.31c1.35.07 2.29.74 3.08.8 1.18-.24 2.31-.93 3.57-.84 1.51.12 2.65.72 3.4 1.8-3.12 1.87-2.38 5.98.48 7.13-.57 1.5-1.31 2.99-2.54 4.09zM12.03 7.25c-.15-2.23 1.66-4.07 3.74-4.25.29 2.58-2.34 4.5-3.74 4.25z"/></svg>
                  App Store
                </a>
                <a href="#" className="btn btn-primary" data-hover style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 10 }}>
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M3.61 1.81L13.42 12 3.61 22.19c-.36-.36-.61-.9-.61-1.48V3.29c0-.58.25-1.12.61-1.48zM14.8 13.38l2.92 1.7-2.07 2.07-2.73-2.73 1.88-1.04zM14.8 10.62l-1.88-1.04 2.73-2.73 2.07 2.07-2.92 1.7zM21.4 11.1l-2.61-1.52-2.38 2.38 2.38 2.38 2.61-1.52c.5-.29.5-1.01 0-1.72z"/></svg>
                  Google Play
                </a>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Modal Devenir Partenaire — formulaire complet pour les transporteurs */}
      {partnerOpen && (
        <div className="ft-modal-backdrop" onClick={() => setPartnerOpen(false)}>
          <div className="ft-modal ft-modal-large" onClick={e => e.stopPropagation()}>
            <button type="button" className="ft-modal-close" onClick={() => setPartnerOpen(false)} data-hover aria-label="Fermer">×</button>
            <div className="ft-modal-head">
              <span className="ft-modal-eyebrow">
                {lang === "fr" ? "Pour les transporteurs" : "For carriers"}
              </span>
              <h3 className="ft-modal-title">
                {lang === "fr" ? "Devenez partenaire FasoTravel" : "Become a FasoTravel partner"}
              </h3>
              <p className="ft-modal-sub" style={{ marginBottom: 24 }}>
                {lang === "fr"
                  ? "Notre équipe vous contacte sous 48h sur WhatsApp pour planifier l'intégration."
                  : "Our team reaches out within 48h on WhatsApp to plan the onboarding."}
              </p>
            </div>
            {!partnerSent ? (
              <form onSubmit={submitPartner} className="ft-modal-form ft-form-grid">
                <label className="ft-field ft-field-full">
                  <span>{lang === "fr" ? "Nom de la société *" : "Company name *"}</span>
                  <input
                    type="text" required
                    value={partnerForm.company}
                    onChange={e => setPartnerForm({ ...partnerForm, company: e.target.value })}
                    placeholder={lang === "fr" ? "TSR, Rakiéta, Sotrao…" : "TSR, Rakiéta, Sotrao…"}
                  />
                </label>
                <label className="ft-field">
                  <span>{lang === "fr" ? "Personne à contacter *" : "Contact person *"}</span>
                  <input
                    type="text" required
                    value={partnerForm.contact}
                    onChange={e => setPartnerForm({ ...partnerForm, contact: e.target.value })}
                    placeholder={lang === "fr" ? "Prénom Nom" : "First Last"}
                  />
                </label>
                <label className="ft-field">
                  <span>{lang === "fr" ? "WhatsApp *" : "WhatsApp *"}</span>
                  <div className="ft-input-phone">
                    <span className="ft-input-prefix">🇧🇫 +226</span>
                    <input
                      type="tel" required inputMode="tel"
                      pattern="[0-9 ]{6,}"
                      value={partnerForm.phone}
                      onChange={e => setPartnerForm({ ...partnerForm, phone: e.target.value })}
                      placeholder="70 00 00 00"
                    />
                  </div>
                </label>
                <label className="ft-field">
                  <span>{lang === "fr" ? "Ville principale" : "Main city"}</span>
                  <input
                    type="text"
                    value={partnerForm.city}
                    onChange={e => setPartnerForm({ ...partnerForm, city: e.target.value })}
                    placeholder={lang === "fr" ? "Ouagadougou" : "Ouagadougou"}
                  />
                </label>
                <label className="ft-field">
                  <span>{lang === "fr" ? "Taille de la flotte" : "Fleet size"}</span>
                  <select
                    value={partnerForm.fleet}
                    onChange={e => setPartnerForm({ ...partnerForm, fleet: e.target.value })}
                  >
                    <option value="">—</option>
                    <option value="1-5">1 – 5</option>
                    <option value="6-15">6 – 15</option>
                    <option value="16-30">16 – 30</option>
                    <option value="31+">31+</option>
                  </select>
                </label>
                <label className="ft-field ft-field-full">
                  <span>{lang === "fr" ? "Message (optionnel)" : "Message (optional)"}</span>
                  <textarea
                    rows={3}
                    value={partnerForm.message}
                    onChange={e => setPartnerForm({ ...partnerForm, message: e.target.value })}
                    placeholder={lang === "fr"
                      ? "Vos lignes principales, vos attentes, questions…"
                      : "Your main routes, expectations, questions…"}
                  />
                </label>
                <button type="submit" className="btn btn-primary ft-field-full" data-hover>
                  {lang === "fr" ? "Envoyer ma candidature" : "Send my application"}
                </button>
              </form>
            ) : (
              <div className="ft-modal-success ft-modal-success-large">
                ✓ {lang === "fr"
                  ? "Candidature reçue. Notre équipe vous contacte sous 48h sur WhatsApp."
                  : "Application received. Our team contacts you within 48h on WhatsApp."}
              </div>
            )}
          </div>
        </div>
      )}
    </>
  );
}

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