// cosmos-app.jsx — écrans de la version soft & cosmique → window.CosmosApp

const C_CONTENT = {
  brand: "YANN DARWIN",
  tag: "La newsletter",
  eyebrow: "Chaque semaine · gratuit",
  titleAccent: "Finances",
  titleRest: " & Investissement,",
  titleB: "mais pas chiant",
  lede: "Je trie et vulgarise tout ce qui bouge dans le monde et ce que ça change pour ton argent. Chaque semaine, en 5 minutes.",
  cta: "Recevoir la newsletter",
  hint: "Zéro spam. Désabonnement en un clic.",
  meta: [
    ["La data", "qui compte"],
    ["5 min", "de lecture"],
    ["0 €", "pour toujours"],
  ],
  social: [
    { id: "youtube", href: "https://www.youtube.com/@YannDarwin", label: "YouTube" },
    { id: "instagram", href: "https://www.instagram.com/yann_darwin/", label: "Instagram" },
    { id: "x", href: "https://x.com/YannDarwin", label: "X" },
    { id: "linkedin", href: "https://www.linkedin.com/in/yann-darwin/", label: "LinkedIn" },
  ],
  legal: "",
};

function navigate(route) {
  if (location.hash !== "#" + route) location.hash = route;
  else window.dispatchEvent(new HashChangeEvent("hashchange"));
  window.scrollTo({ top: 0, behavior: "auto" });
}

/* ---------- envoi vers l'API (Railway) ---------- */
// API servie par le même service que le site → même origine, chemin absolu.
const API_BASE = "";

async function postSubscribe(payload) {
  const r = await fetch(API_BASE + "/api/subscribe", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(payload),
  });
  if (!r.ok) throw new Error("HTTP " + r.status);
  return r.json().catch(() => ({}));
}

// File d'attente locale : si l'envoi échoue (réseau/serveur), on ne perd RIEN.
function queuePending(payload) {
  try {
    const q = JSON.parse(localStorage.getItem("yd_pending") || "[]");
    q.push({ ...payload, ts: Date.now() });
    localStorage.setItem("yd_pending", JSON.stringify(q));
  } catch (e) {}
}
async function flushPending() {
  let q;
  try { q = JSON.parse(localStorage.getItem("yd_pending") || "[]"); } catch (e) { return; }
  if (!q.length) return;
  const remaining = [];
  for (const item of q) {
    try { await postSubscribe(item); } catch (e) { remaining.push(item); }
  }
  try { localStorage.setItem("yd_pending", JSON.stringify(remaining)); } catch (e) {}
}

/* ---------- icônes ---------- */
function Arrow() {
  return (<svg className="arrow" width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M2 8h11M9 4l4 4-4 4" /></svg>);
}
function ArrowBack() {
  return (<svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round"><path d="M14 8H3M7 4 3 8l4 4" /></svg>);
}
function Spark() {
  return (<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2l1.6 6.4L20 10l-6.4 1.6L12 18l-1.6-6.4L4 10l6.4-1.6L12 2z" /></svg>);
}
function LinkIcon() {
  return (<svg width="15" height="15" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M6.5 9.5a2.5 2.5 0 0 0 3.5 0l2-2a2.5 2.5 0 0 0-3.5-3.5l-1 1" /><path d="M9.5 6.5a2.5 2.5 0 0 0-3.5 0l-2 2a2.5 2.5 0 0 0 3.5 3.5l1-1" /></svg>);
}
function CheckIcon() {
  return (<svg width="15" height="15" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 8.5 6.5 12 13 4.5" /></svg>);
}
function SocialIcon({ id }) {
  const p = { width: 17, height: 17, viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": true };
  if (id === "youtube") return (<svg {...p}><path d="M23 12s0-3.2-.4-4.7a2.5 2.5 0 0 0-1.8-1.8C19.2 5 12 5 12 5s-7.2 0-8.8.5A2.5 2.5 0 0 0 1.4 7.3C1 8.8 1 12 1 12s0 3.2.4 4.7a2.5 2.5 0 0 0 1.8 1.8C4.8 19 12 19 12 19s7.2 0 8.8-.5a2.5 2.5 0 0 0 1.8-1.8C23 15.2 23 12 23 12zM9.8 15.1V8.9l5.4 3.1-5.4 3.1z"/></svg>);
  if (id === "instagram") return (<svg {...p} fill="none" stroke="currentColor" strokeWidth="1.8"><rect x="3" y="3" width="18" height="18" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.3" cy="6.7" r="1.1" fill="currentColor" stroke="none"/></svg>);
  if (id === "x") return (<svg {...p}><path d="M17.5 3h3.2l-7 8 8.2 10h-6.4l-5-6.1L8.8 21H5.6l7.5-8.6L5.3 3h6.6l4.5 5.6L17.5 3zm-1.1 16h1.8L7.7 4.8H5.8L16.4 19z"/></svg>);
  if (id === "linkedin") return (<svg {...p}><path d="M4.5 3.5a2 2 0 1 0 0 4 2 2 0 0 0 0-4zM3 9h3v12H3V9zm6 0h2.9v1.6h.04c.4-.76 1.4-1.6 2.9-1.6 3.1 0 3.7 2 3.7 4.7V21h-3v-5.5c0-1.3 0-3-1.85-3S13.8 14 13.8 15.4V21h-3V9z"/></svg>);
  return null;
}

/* ---------- chrome ---------- */
function TopBar() {
  return (
    <header className="topbar">
      <div className="topbar-in">
        <a className="brand" onClick={() => navigate("/")}>
          <img src="site/yd-logo.png" alt="Yann Darwin" />
          <span>{C_CONTENT.brand}</span>
        </a>
        <span className="sub">{C_CONTENT.tag}</span>
      </div>
    </header>
  );
}
function Foot() {
  return (
    <footer className="foot">
      <div className="foot-in">
        <span className="finehint">{C_CONTENT.legal}</span>
        <div className="social-row">
          {C_CONTENT.social.map((s) => (
            <a key={s.id} className="social-link" href={s.href} target="_blank" rel="noreferrer" aria-label={s.label}>
              <SocialIcon id={s.id} />
            </a>
          ))}
        </div>
      </div>
    </footer>
  );
}

/* ---------- LANDING (minimale) ---------- */
function Landing() {
  const [email, setEmail] = React.useState("");
  const [err, setErr] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const c = C_CONTENT;

  const go = async (e) => {
    e.preventDefault();
    if (!/.+@.+\..+/.test(email)) { setErr("Entre une adresse email valide."); return; }
    setErr("");
    setBusy(true);
    const payload = { email: email.trim().toLowerCase(), source: "newsletter" };
    try {
      await postSubscribe(payload);
    } catch (err2) {
      // échec réseau/serveur : on garde l'inscription en local pour la renvoyer plus tard
      queuePending(payload);
    } finally {
      setBusy(false);
      navigate("/merci");
    }
  };

  return (
    <div className="cosmos route-anim" data-screen-label="Landing">
      <TopBar />
      <section className="hero wrap">
        <span className="eyebrow"><span className="dot" />{c.eyebrow}</span>
        <h1 className="display glow-text">
          <span className="accent-text">{c.titleAccent}</span>{c.titleRest}<br /><span className="accent-text">{c.titleB}</span>
        </h1>
        <p className="lede">{c.lede}</p>

        <div className="hero-cta">
          <form className="inline-form" onSubmit={go}>
            <input className="field" type="email" placeholder="ton@email.com" value={email}
                   onChange={(e) => setEmail(e.target.value)} aria-label="Email" />
            <button className="btn" type="submit" disabled={busy}>{busy ? "Envoi…" : c.cta} <Arrow /></button>
          </form>
          {err ? <span className="finehint err">{err}</span> : <span className="finehint">{c.hint}</span>}
        </div>

        <div className="hero-meta">
          {c.meta.map(([n, l]) => (
            <span className="pellet" key={l}><Spark /> <b style={{ color: "var(--fg)" }}>{n}</b> {l}</span>
          ))}
        </div>
      </section>
      <Foot />
    </div>
  );
}

/* ---------- MERCI ---------- */
function Thanks() {
  const [copied, setCopied] = React.useState(false);
  const copyLink = () => {
    const url = location.origin + location.pathname;
    try {
      if (navigator.clipboard && navigator.clipboard.writeText) navigator.clipboard.writeText(url).catch(() => {});
      const ta = document.createElement("textarea"); ta.value = url; ta.style.position = "fixed"; ta.style.opacity = "0";
      document.body.appendChild(ta); ta.focus(); ta.select(); try { document.execCommand("copy"); } catch (e) {} document.body.removeChild(ta);
    } catch (e) {}
    setCopied(true); setTimeout(() => setCopied(false), 2200);
  };
  return (
    <div className="cosmos" data-screen-label="Merci">
      <TopBar />
      <div className="center-page wrap">
        <div className="card center route-anim">
          <div className="thanks-badge">✓</div>
          <h1>Encore une étape</h1>
          <p className="lede">Clique sur le lien de confirmation qui t'attend dans ta boite mail (pense à vérifier les spams et whitelister les emails).</p>
          <p className="finehint thanks-share">
            <span>Recommander cette newsletter ? Lien de partage ici</span>
            <button type="button" className="copy-inline" onClick={copyLink} aria-label={copied ? "Lien copié" : "Copier le lien"} title={copied ? "Lien copié" : "Copier le lien"}>
              {copied ? <CheckIcon /> : <LinkIcon />}
            </button>
          </p>
        </div>
      </div>
      <Foot />
    </div>
  );
}

Object.assign(window, { C_CONTENT, navigate, Landing, Thanks });

// renvoie d'éventuelles inscriptions mises en file lors d'un échec réseau précédent
try { flushPending(); } catch (e) {}
