// EELAJ — Landing coming-soon
// Single-file React app rendered into #root.

const { useState, useEffect, useRef } = React;

// ─── Google Sheet webhook ──────────────────────────────────────────────────
// Remplacez la valeur ci-dessous par l'URL fournie après le déploiement de
// google-apps-script.gs (voir instructions dans ce fichier). Tant que la
// valeur commence par "REMPLACE_", le formulaire fonctionne en mode démo
// (simulation, aucun email n'est envoyé).
const SHEET_WEBHOOK_URL = "https://script.google.com/macros/s/AKfycbztxo785JQkqtdIW_KlZA0fmy0CWLJTG9BOuKKTONv7nc1rQtlK2TeM1BSN_UCEIIUp/exec";

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "layout": "centered",
  "accent": "#D9936C",
  "ambiance": "ivoire",
  "showIngredients": true,
  "showBottle": true,
  "showTexture": true,
  "headerStyle": "minimal"
}/*EDITMODE-END*/;

// Palette de la charte
const PALETTE = {
  ivoire: "#FDF3EA",
  terreCuite: "#D9936C",
  vert: "#C8D4B3",
  beige: "#BBB8A7",
  orange: "#E8A868",
  ink: "#3C342B",
  inkSoft: "#6B5F52",
  // nuances
  terraSoft1: "#FFE9DD",
  terraSoft2: "#EDCDBB",
  neutralSoft: "#E8E7E2",
};

// ─── Header ──────────────────────────────────────────────────────────────────
function Header({ accent, onNotifyClick, headerStyle }) {
  return (
    <header className="hdr">
      <div className="hdr-inner">
        <a href="#" className="hdr-logo" aria-label="EELAJ — Accueil">
          <img src="assets/eelaj-icon.png" alt="EELAJ" className="hdr-icon" />
        </a>
        <nav className="hdr-nav" aria-label="Navigation principale">
          <a href="#accueil" className="nav-link nav-active">Accueil</a>
          <a href="#marque" className="nav-link">La marque</a>
          <a href="#ingredients" className="nav-link">Ingrédients</a>
          <a href="#contact" className="nav-link">Contact</a>
        </nav>
        <button
          type="button"
          className="hdr-cta"
          onClick={onNotifyClick}
          style={{ borderColor: accent, color: accent }}
        >
          <span className="dot" style={{ background: accent }}></span>
          Être prévenu
        </button>
      </div>
    </header>
  );
}

// Wordmark — real EELAJ logo (PNG outline, tinted via CSS filter)
function Wordmark({ color = "#D9936C", size = 28 }) {
  return (
    <span className="wordmark" style={{ height: size }}>
      <img src="assets/eelaj-logo.png" alt="EELAJ" className="wordmark-img" />
    </span>
  );
}

// ─── Hero ────────────────────────────────────────────────────────────────────
function Hero({ accent, layout, showIngredients, showBottle, ambiance }) {
  return (
    <section className={`hero hero-${layout} amb-${ambiance}`} id="accueil">
      {/* Background organic blobs */}
      <div className="blobs" aria-hidden="true">
        <span className="blob blob-1" style={{ background: PALETTE.vert }}></span>
        <span className="blob blob-2" style={{ background: PALETTE.terraSoft1 }}></span>
        <span className="blob blob-3" style={{ background: PALETTE.neutralSoft }}></span>
      </div>

      <div className="hero-grid">
        <div className="hero-copy">
          <div className="hero-mark">
            <img src="assets/eelaj-logo.png" alt="EELAJ" />
          </div>
          <div className="hero-eyebrow">
            <span className="eyebrow-line" style={{ background: accent }}></span>
            <span className="eyebrow-text">Bientôt disponible — Édition fondatrice</span>
          </div>
          <h1 className="hero-title">
            <span className="t-line">La boutique</span>
            <span className="t-line t-italic"><em>arrive</em> bientôt</span>
          </h1>
          <p className="hero-sub">
            Des compléments naturels pensés pour prendre soin
            <br className="hide-mobile" />
            de vous et de vos proches.
          </p>

          <NotifyForm accent={accent} />

          <ul className="reassure">
            <li>Naturel</li>
            <li className="dot-sep" aria-hidden="true">•</li>
            <li>Confiance</li>
            <li className="dot-sep" aria-hidden="true">•</li>
            <li>Sérénité</li>
            <li className="dot-sep" aria-hidden="true">•</li>
            <li>Vitalité</li>
          </ul>

          <div className="kids-badge">
            <span className="kids-icon" style={{ background: PALETTE.vert }}></span>
            <span>Formule <strong>Kids</strong> en préparation</span>
          </div>
        </div>

        {layout !== "centered" && (
          <div className="hero-visual">
            <HeroVisual accent={accent} showBottle={showBottle} showIngredients={showIngredients} />
          </div>
        )}
      </div>

      {layout === "centered" && (
        <>
          {showIngredients && <FloatingIngredients accent={accent} />}
          {showBottle && (
            <div className="bottle-floating">
              <BottleSilhouette accent={accent} />
            </div>
          )}
        </>
      )}
    </section>
  );
}

// ─── Email form with validation + success state ──────────────────────────────
function NotifyForm({ accent }) {
  const [email, setEmail] = useState("");
  const [status, setStatus] = useState("idle"); // idle | error | submitting | success
  const [error, setError] = useState("");
  const inputRef = useRef(null);

  const validate = (e) => /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(e.trim());

  const submit = (ev) => {
    ev.preventDefault();
    if (status === "submitting" || status === "success") return;
    if (!validate(email)) {
      setStatus("error");
      setError(email.trim() === "" ? "Merci de renseigner votre email." : "Cet email ne semble pas valide.");
      inputRef.current?.focus();
      return;
    }
    setStatus("submitting");
    setError("");

    const isConfigured = SHEET_WEBHOOK_URL && !SHEET_WEBHOOK_URL.startsWith("REMPLACE_");
    if (!isConfigured) {
      // Mode démo : aucun backend connecté
      setTimeout(() => setStatus("success"), 900);
      return;
    }

    // Mode réel : POST vers le webhook Google Apps Script.
    // text/plain évite le preflight CORS (le body reste un JSON).
    fetch(SHEET_WEBHOOK_URL, {
      method: "POST",
      mode: "cors",
      headers: { "Content-Type": "text/plain;charset=utf-8" },
      body: JSON.stringify({
        email: email.trim(),
        source: "landing-coming-soon",
        ua: navigator.userAgent,
      }),
    })
      .then((r) => r.json().catch(() => ({ ok: r.ok })))
      .then((res) => {
        if (res && res.ok) {
          setStatus("success");
        } else {
          setStatus("error");
          setError("Impossible d'enregistrer pour le moment. Réessayez dans un instant.");
        }
      })
      .catch(() => {
        setStatus("error");
        setError("Connexion impossible. Vérifiez votre réseau.");
      });
  };

  if (status === "success") {
    return (
      <div className="form-success" role="status" aria-live="polite">
        <div className="success-mark" style={{ borderColor: accent, color: accent }}>
          <svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true">
            <path d="M5 12.5l4.5 4.5L19 7" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </div>
        <div className="success-copy">
          <strong>Merci.</strong> Nous vous écrivons dès l'ouverture
          <span className="success-email"> ({email})</span>.
        </div>
      </div>
    );
  }

  return (
    <form className={`notify-form ${status === "error" ? "has-error" : ""}`} onSubmit={submit} noValidate>
      <div className="field">
        <input
          ref={inputRef}
          type="email"
          inputMode="email"
          autoComplete="email"
          className="input"
          placeholder="Votre email"
          aria-label="Votre adresse email"
          value={email}
          onChange={(e) => { setEmail(e.target.value); if (status === "error") setStatus("idle"); }}
        />
        <button
          type="submit"
          className="btn-primary"
          style={{ background: accent }}
          disabled={status === "submitting"}
        >
          {status === "submitting" ? (
            <span className="spinner" aria-hidden="true"></span>
          ) : (
            <>
              Être prévenu
              <svg viewBox="0 0 20 20" width="14" height="14" aria-hidden="true" style={{ marginLeft: 8 }}>
                <path d="M3 10h13M11 5l5 5-5 5" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </>
          )}
        </button>
      </div>
      <div className="form-meta">
        {status === "error" ? (
          <span className="form-error">{error}</span>
        ) : (
          <span className="form-hint">Aucun spam. Une seule notification, à l'ouverture.</span>
        )}
      </div>
    </form>
  );
}

// ─── Decorative: floating real-ingredient photos ────────────────────────────
const INGREDIENT_ITEMS = [
  { label: "miel",    src: "assets/ingredients/miel.png",    cls: "ing-miel"    },
  { label: "grenade", src: "assets/ingredients/grenade.png", cls: "ing-grenade" },
  { label: "raisin",  src: "assets/ingredients/raisin.png",  cls: "ing-raisin"  },
  { label: "citron",  src: "assets/ingredients/citron.png",  cls: "ing-citron"  },
  { label: "olive",   src: "assets/ingredients/olive.png",   cls: "ing-olive"   },
  { label: "date",    src: "assets/ingredients/date.png",    cls: "ing-date"    },
];

function FloatingIngredients() {
  return (
    <div className="ingredients" aria-hidden="true">
      {INGREDIENT_ITEMS.map((it) => (
        <div key={it.label} className={`ing ${it.cls}`}>
          <img src={it.src} alt="" loading="lazy" />
        </div>
      ))}
    </div>
  );
}

// ─── Bottle silhouette (simple shapes only) ──────────────────────────────────
function BottleSilhouette({ accent }) {
  return (
    <svg viewBox="0 0 120 200" className="bottle" aria-hidden="true">
      {/* cap */}
      <rect x="46" y="6" width="28" height="22" rx="3" fill="none" stroke={accent} strokeWidth="1.2" />
      {/* neck */}
      <rect x="50" y="26" width="20" height="14" fill="none" stroke={accent} strokeWidth="1.2" />
      {/* body */}
      <rect x="22" y="40" width="76" height="148" rx="14" fill="none" stroke={accent} strokeWidth="1.2" />
      {/* label */}
      <rect x="30" y="86" width="60" height="64" rx="2" fill="none" stroke={accent} strokeWidth="0.8" strokeDasharray="2 3" opacity="0.6" />
      {/* wordmark mini */}
      <text x="60" y="120" textAnchor="middle" fontFamily="'Cormorant Garamond', serif" fontSize="14" fill={accent} opacity="0.9">eelaj</text>
      <line x1="44" y1="132" x2="76" y2="132" stroke={accent} strokeWidth="0.6" opacity="0.5" />
      <text x="60" y="144" textAnchor="middle" fontFamily="'JetBrains Mono', monospace" fontSize="5" letterSpacing="1" fill={accent} opacity="0.6">FORMULE NATURELLE</text>
    </svg>
  );
}

// Hero visual used for split layout
function HeroVisual({ accent, showBottle, showIngredients }) {
  return (
    <div className="visual-stage">
      <div className="visual-bg" style={{ background: `linear-gradient(160deg, ${PALETTE.terraSoft1} 0%, ${PALETTE.vert} 100%)` }}>
        <div className="visual-grain"></div>
      </div>
      {showBottle && (
        <div className="visual-bottle">
          <BottleSilhouette accent={accent} />
        </div>
      )}
      {showIngredients && (
        <>
          <div className="v-ing v-ing-1"><img src="assets/ingredients/miel.png"    alt="" /></div>
          <div className="v-ing v-ing-2"><img src="assets/ingredients/grenade.png" alt="" /></div>
          <div className="v-ing v-ing-3"><img src="assets/ingredients/raisin.png"  alt="" /></div>
          <div className="v-ing v-ing-4"><img src="assets/ingredients/citron.png"  alt="" /></div>
        </>
      )}
      <div className="visual-tag">
        <span className="tag-dot" style={{ background: accent }}></span>
        <span>100% naturel · sans codes médicaux</span>
      </div>
    </div>
  );
}

// ─── Footer (very minimal — coming soon) ─────────────────────────────────────
function FooterMini({ accent }) {
  return (
    <footer className="ft">
      <div className="ft-inner">
        <div className="ft-left">
          <Wordmark color={accent} size={18} />
          <span className="ft-sep">·</span>
          <span className="ft-meta">© 2026 — Tous droits réservés</span>
        </div>
        <div className="ft-right">
          <span className="ft-hint">Compléments alimentaires naturels — Famille</span>
        </div>
      </div>
    </footer>
  );
}

// ─── App root ────────────────────────────────────────────────────────────────
function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const formRef = useRef(null);

  // Apply ambiance + texture toggles at body level
  useEffect(() => {
    document.body.dataset.ambiance = t.ambiance;
    document.body.dataset.texture = t.showTexture ? "on" : "off";
  }, [t.ambiance, t.showTexture]);

  const scrollToForm = () => {
    const el = document.querySelector(".notify-form, .form-success");
    if (el) el.scrollIntoView({ behavior: "smooth", block: "center" });
  };

  return (
    <div className="page" style={{ "--accent": t.accent }}>
      <Header accent={t.accent} onNotifyClick={scrollToForm} headerStyle={t.headerStyle} />
      <main>
        <Hero
          accent={t.accent}
          layout={t.layout}
          showIngredients={t.showIngredients}
          showBottle={t.showBottle}
          ambiance={t.ambiance}
        />
      </main>
      <FooterMini accent={t.accent} />

      <TweaksPanel title="Tweaks">
        <TweakSection label="Layout" />
        <TweakRadio
          label="Composition"
          value={t.layout}
          options={["centered", "split", "banded"]}
          onChange={(v) => setTweak("layout", v)}
        />
        <TweakSection label="Couleurs" />
        <TweakColor
          label="Accent"
          value={t.accent}
          options={["#D9936C", "#E8A868", "#BBB8A7", "#A8B58F"]}
          onChange={(v) => setTweak("accent", v)}
        />
        <TweakRadio
          label="Ambiance"
          value={t.ambiance}
          options={["ivoire", "vert", "terre"]}
          onChange={(v) => setTweak("ambiance", v)}
        />
        <TweakSection label="Visuels" />
        <TweakToggle label="Ingrédients flottants" value={t.showIngredients} onChange={(v) => setTweak("showIngredients", v)} />
        <TweakToggle label="Silhouette flacon" value={t.showBottle} onChange={(v) => setTweak("showBottle", v)} />
        <TweakToggle label="Texture papier" value={t.showTexture} onChange={(v) => setTweak("showTexture", v)} />
      </TweaksPanel>
    </div>
  );
}

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