/* ClientBase, Homepage part 2: Beta pitch, Final CTA, HomePage */

// ============ COMPTEUR LIVE D'UTILISATEURS ============
// Stratégie : on appelle la RPC Supabase `get_public_user_counts()` UNE
// SEULE FOIS au premier mount, puis on cache le résultat dans
// window.__cbUserCounts pour que les autres montages du badge n'aient
// pas à refaire l'appel.
//
// Fallback déterministe si Supabase est offline OU si la RPC n'est pas
// (encore) déployée (migration 017) : un compteur baseline qui progresse
// dans le temps, pour que le badge ne disparaisse jamais visuellement.
const cbFallbackCount = () => {
  const anchor = new Date("2026-05-01T00:00:00").getTime();
  const now = Date.now();
  const days = Math.max(0, (now - anchor) / 86400000);
  const hourSeed = (new Date().getHours() * 7) % 4;
  return Math.floor(247 + days * 0.85) + hourSeed;
};

// Promise mémoïsée avec TTL : un seul appel réseau par fenêtre de 30s,
// partagé par tous les composants qui montent un LiveProsBadge. Au-delà
// du TTL, le prochain appel refait la RPC pour refléter les suppressions
// de comptes côté admin (sinon le badge resterait à l'ancien chiffre
// pendant toute la session). Renvoie { pros, clients, total }.
const _CB_USER_COUNTS_TTL = 30_000;
const cbFetchUserCounts = (force = false) => {
  const now = Date.now();
  if (!force
      && window.__cbUserCountsPromise
      && window.__cbUserCountsAt
      && (now - window.__cbUserCountsAt) < _CB_USER_COUNTS_TTL) {
    return window.__cbUserCountsPromise;
  }
  window.__cbUserCountsAt = now;
  window.__cbUserCountsPromise = (async () => {
    const fb = cbFallbackCount();
    const fallback = { pros: fb, clients: 0, total: fb, real: false };
    try {
      if (!window.cbSupabase) return fallback;
      const { data, error } = await window.cbSupabase.rpc("get_public_user_counts");
      if (error || !data) return fallback;
      const row = Array.isArray(data) ? data[0] : data;
      if (!row) return fallback;
      const pros    = Number(row.pros)    || 0;
      const clients = Number(row.clients) || 0;
      const total   = Number(row.total)   || (pros + clients);
      return { pros, clients, total, real: true };
    } catch {
      return fallback;
    }
  })();
  return window.__cbUserCountsPromise;
};
// Invalidation manuelle (utilisée par admin après une suppression).
const cbInvalidateUserCounts = () => {
  try { window.__cbUserCountsPromise = null; window.__cbUserCountsAt = 0; } catch {}
};

// Badge live « X utilisateurs sur ClientBase ». Réutilisable partout :
// hero, BetaPitch, AuthShell, vitrine client. S'anime au scroll grâce au
// useCountUp partagé. Le tone par défaut est indigo (var(--accent)) ;
// passer tone="var(--cli-accent)" pour la version violette client.
//
// Props :
//   - tone         : couleur d'accent du badge
//   - compact      : version plus petite (auth shell)
//   - role         : "pro" | "client" | "all" (defaut "all") → chiffre affiché
//   - labelSuffix  : libellé après le nombre (defaut "utilisateurs sur ClientBase")
const LiveProsBadge = ({
  tone = "var(--accent)",
  compact = false,
  role = "all",
  labelSuffix,
} = {}) => {
  // On démarre avec le fallback déterministe (pour avoir tout de suite
  // quelque chose à animer), puis on remplace par le vrai chiffre dès
  // que la RPC répond.
  const [target, setTarget] = React.useState(() => cbFallbackCount());
  React.useEffect(() => {
    let alive = true;
    const apply = (r) => {
      if (!alive) return;
      const v = role === "pro" ? r.pros
              : role === "client" ? r.clients
              : r.total;
      setTarget(Math.max(0, v));
    };
    cbFetchUserCounts().then(apply);
    // Re-fetch quand l'utilisateur revient sur l'onglet : si un admin a
    // supprimé un compte dans une autre fenêtre, le badge se mettra à jour
    // dès qu'on retourne sur la page (TTL court + invalidation au focus).
    const onFocus = () => { cbFetchUserCounts(true).then(apply); };
    window.addEventListener("focus", onFocus);
    document.addEventListener("visibilitychange", onFocus);
    return () => {
      alive = false;
      window.removeEventListener("focus", onFocus);
      document.removeEventListener("visibilitychange", onFocus);
    };
  }, [role]);

  const useCU = window.useCountUp;
  const fallbackRef = React.useRef(null);
  const [count, ref] = useCU ? useCU(target, { duration: 1400 }) : [target, fallbackRef];
  const suffix = labelSuffix || "utilisateurs sur ClientBase";
  return (
    <span ref={ref} style={{
      display: "inline-flex", alignItems: "center", gap: 7,
      padding: compact ? "3px 10px 3px 8px" : "5px 12px 5px 10px",
      background: "var(--surface)",
      border: `1px solid color-mix(in oklab, ${tone} 32%, var(--line))`,
      borderRadius: 999,
      fontSize: compact ? 11.5 : 12.5, fontWeight: 540,
      // Tout le badge (chiffre + texte) en couleur d'audience pour
      // une preuve sociale parfaitement lisible et unifiée :
      // indigo plein côté pro, cli-accent côté client.
      color: tone,
      fontVariantNumeric: "tabular-nums",
    }}>
      <span aria-hidden style={{
        width: 7, height: 7, borderRadius: 50, background: tone,
        animation: "cbPulse 1.8s ease-in-out infinite",
      }}/>
      <strong style={{ fontWeight: 700, color: tone }}>
        {count.toLocaleString("fr-FR")}
      </strong>
      {suffix}
    </span>
  );
};
if (typeof window !== "undefined") {
  window.LiveProsBadge = LiveProsBadge;
  window.cbFetchUserCounts = cbFetchUserCounts;
  window.cbInvalidateUserCounts = cbInvalidateUserCounts;
}


/* -------- BETA TESTERS, invitation card with benefits -------- */
const BetaPitch = ({ go }) => (
  <section style={{ padding: "32px 0 80px" }}>
    <style>{`
      @keyframes cbPulse {
        0%, 100% { opacity: 1; transform: scale(1); }
        50% { opacity: 0.6; transform: scale(1.3); }
      }
    `}</style>
    <div className="container">
      <div style={{
        maxWidth: 580, margin: "0 auto",
        background: "var(--surface)",
        border: "1px solid var(--line-strong)",
        borderRadius: 24,
        boxShadow: "var(--sh-3)",
        position: "relative",
        overflow: "hidden",
      }}>
        {/* Decorative accent, top-right bloom */}
        <div aria-hidden style={{
          position: "absolute", top: -100, right: -100,
          width: 260, height: 260, borderRadius: "50%",
          background: "radial-gradient(circle, var(--accent-soft) 0%, transparent 70%)",
          pointerEvents: "none",
        }}/>
        {/* Top accent strip — indigo solide (couleur de marque). */}
        <div aria-hidden style={{
          height: 4,
          background: "var(--accent)",
        }}/>

        {/* Bouton raccourci compact en coin haut-droite : pour les visiteurs
            qui ont déjà lu et veulent sauter direct à l'inscription. Distinct
            visuellement du CTA principal (plus petit, pill). */}
        <button
          onClick={() => go("signup")}
          className="cb-betapitch-shortcut"
          style={{
            position: "absolute", top: 16, right: 16, zIndex: 3,
            display: "inline-flex", alignItems: "center", gap: 6,
            padding: "7px 14px 7px 12px",
            background: "var(--accent-soft)",
            color: "var(--accent-ink)",
            border: "1px solid color-mix(in oklab, var(--accent) 28%, transparent)",
            borderRadius: 999,
            fontSize: 12.5, fontWeight: 540, fontFamily: "inherit",
            cursor: "pointer",
            transition: "transform .12s ease, background .15s ease, box-shadow .15s ease",
          }}
          onMouseEnter={(e) => {
            e.currentTarget.style.background = "var(--accent-soft-2)";
            e.currentTarget.style.transform = "translateY(-1px)";
            e.currentTarget.style.boxShadow = "0 6px 16px -8px var(--accent)";
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.background = "var(--accent-soft)";
            e.currentTarget.style.transform = "translateY(0)";
            e.currentTarget.style.boxShadow = "none";
          }}>
          <Icon name="arrow" size={11}/>
          Raccourci inscription
        </button>

        <div style={{ padding: "36px 32px", position: "relative" }}>
          <div style={{ textAlign: "center" }}>
            {/* Live counter : remplace l'ancien badge statique « Bêta ouverte »
                par une preuve sociale dynamique qui s'incrémente au fil des
                jours et anime au scroll (useCountUp). */}
            <LiveProsBadge tone="var(--accent)"/>
            <h2 style={{
              marginTop: 18,
              fontSize: "clamp(28px, 3.4vw, 40px)", letterSpacing: "-0.03em",
              lineHeight: 1.05,
            }}>
              On vous réserve <br/>
              <span style={{ position: "relative", display: "inline-block" }}>
                <span aria-hidden style={{
                  position: "absolute", zIndex: 0,
                  left: "-4%", right: "-4%", bottom: "0.06em",
                  height: "0.36em",
                  background: "linear-gradient(90deg, color-mix(in oklab, var(--accent) 22%, transparent) 0%, color-mix(in oklab, var(--accent) 35%, transparent) 100%)",
                  borderRadius: "0.16em",
                }}/>
                <span style={{ position: "relative", zIndex: 1 }}>une place.</span>
              </span>
            </h2>
            <p style={{
              marginTop: 14, fontSize: 15, color: "var(--ink-2)",
              lineHeight: 1.55, maxWidth: 420, margin: "14px auto 0",
            }}>
              Rejoignez les premiers utilisateurs et contribuez à créer l'outil qui va vous simplifier le quotidien.
            </p>
          </div>

          {/* Benefits checklist, palette canonique cyclée (sauge, indigo,
              rose, indigo) pour rythme sans casser la cohérence. */}
          <ul style={{
            listStyle: "none", padding: 0, margin: "26px 0 0",
            display: "flex", flexDirection: "column", gap: 10,
          }}>
            {/* Tous les icônes (et le ✓) en accent indigo brand : on ne
                cycle plus sur sage/accent/rose, ça donnait un patchwork.
                Bleu uniforme = cohérence visuelle + signal de marque. */}
            {[
              ["euro",     "Gratuit pendant toute la bêta"],
              ["sparkle",  "Mise en place gratuite avec votre fichier clients"],
              ["chat",     "Accès direct à l'équipe pour vos retours"],
              ["shield",   "Données hébergées en France, conformes RGPD"],
            ].map(([icon, text]) => (
              <li key={text} style={{
                display: "flex", alignItems: "center", gap: 12,
                padding: "10px 14px",
                background: "var(--bg-alt)", borderRadius: 10,
                fontSize: 14, color: "var(--ink-2)",
              }}>
                <span style={{
                  width: 30, height: 30, borderRadius: 8,
                  background: "var(--accent-soft)", color: "var(--accent-ink)",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  flexShrink: 0, border: "1px solid transparent",
                }}>
                  <Icon name={icon} size={14}/>
                </span>
                <span style={{ flex: 1 }}>{text}</span>
                <Icon name="check" size={14} stroke={2.6} style={{ color: "var(--accent)", flexShrink: 0 }}/>
              </li>
            ))}
          </ul>

          {/* CTAs */}
          <div style={{ marginTop: 24, display: "flex", flexDirection: "column", gap: 8 }}>
            <button className="btn btn-accent btn-lg" onClick={() => go("signup")} style={{ width: "100%" }}>
              Créer mon compte gratuit <Icon name="arrow" size={15}/>
            </button>
            <button className="btn btn-ghost btn-lg" onClick={() => go("login")} style={{ width: "100%" }}>
              J'ai déjà un compte
            </button>
            <button className="btn btn-ghost btn-lg" onClick={() => go("contact")} style={{ width: "100%", border: "none" }}>
              J'ai une question
            </button>
          </div>

          <div style={{
            marginTop: 18, textAlign: "center",
            display: "flex", alignItems: "center", justifyContent: "center",
            gap: 6, fontSize: 12, color: "var(--ink-4)",
          }}>
            <Icon name="clock" size={11}/>
            Moins de 2 minutes. Sans carte bancaire.
          </div>
        </div>
      </div>
    </div>
  </section>
);

/* -------- FINAL CTA -------- */
const FinalCTA = ({ go }) => (
  <section className="section">
    <div className="container">
      <div style={{
        position: "relative", overflow: "hidden",
        padding: "72px 48px",
        background: "var(--ink)",
        color: "var(--bg)",
        borderRadius: 24,
        textAlign: "center",
      }} className="final-cta">
        <div aria-hidden style={{
          position: "absolute", inset: 0,
          backgroundImage: "radial-gradient(circle at 1px 1px, rgba(255,255,255,0.08) 1px, transparent 0)",
          backgroundSize: "28px 28px",
          maskImage: "radial-gradient(ellipse 80% 60% at 50% 0%, black, transparent 70%)",
          WebkitMaskImage: "radial-gradient(ellipse 80% 60% at 50% 0%, black, transparent 70%)",
        }}/>
        <div style={{ position: "relative" }}>
          <div style={{
            display: "inline-flex", alignItems: "center", gap: 8,
            padding: "5px 12px 5px 8px",
            borderRadius: 999,
            background: "rgba(255,255,255,0.08)",
            color: "oklch(85% 0.15 268)",
            fontSize: 12.5, fontWeight: 500,
          }}>
            <span style={{ width: 6, height: 6, borderRadius: 50, background: "oklch(85% 0.15 268)" }}/>
            Gratuit pendant la bêta · sans carte bancaire
          </div>
          <h2 style={{
            color: "var(--bg)", marginTop: 20,
            fontSize: "clamp(32px, 4vw, 52px)", letterSpacing: "-0.03em",
          }}>
            Prêt à simplifier votre business&nbsp;?
          </h2>
          <p style={{ color: "oklch(78% 0.02 260)", marginTop: 16, fontSize: 17, maxWidth: 520, marginLeft: "auto", marginRight: "auto" }}>
            Installation en 10 minutes. Importez vos clients depuis Excel. On vous accompagne en direct si besoin.
          </p>
          <div style={{ marginTop: 32, display: "flex", gap: 10, justifyContent: "center", flexWrap: "wrap" }}>
            <button className="btn btn-lg" style={{ background: "var(--bg)", color: "var(--ink)" }} onClick={() => go("signup")}>
              Rejoindre la bêta <Icon name="arrow" size={16}/>
            </button>
            <button className="btn btn-lg btn-ghost" style={{ borderColor: "rgba(255,255,255,0.2)", color: "var(--bg)" }} onClick={() => go("contact")}>
              Parler à un humain
            </button>
          </div>
        </div>
      </div>
    </div>
  </section>
);

const HomePage = ({ go, heroVariant }) => (
  <>
    <Hero go={go} variant={heroVariant}/>
    <div className="container" style={{ textAlign: "center" }}>
      <FlowArrow step={2} totalSteps={3}
        caption="Ensuite, estimons ce que ClientBase peut vous rapporter"/>
    </div>
    <Reveal><SavingsSimulator/></Reveal>
    <div className="container" style={{ textAlign: "center" }}>
      <FlowArrow step={3} totalSteps={3}
        caption="On y va ? La bêta est ouverte, profitez-en maintenant"/>
    </div>
    <Reveal><BetaPitch go={go}/></Reveal>
  </>
);

Object.assign(window, { BetaPitch, FinalCTA, HomePage });
