// Shared components for Gestopia

const { useState, useEffect, useRef } = React;

// ─────────────────────────────────────────────────────────────
// LogoMark — the real Gestopia G mark (PNG).
// ─────────────────────────────────────────────────────────────
function LogoMark({ size = 28, style }) {
  return (
    <img
      src="assets/gestopia-mark.png"
      alt=""
      aria-hidden="true"
      width={size}
      height={size}
      style={{
        width: size,
        height: size,
        objectFit: "contain",
        display: "block",
        ...style,
      }}
    />
  );
}

// Logo lockup (mark + wordmark) used in nav and footer.
function Logo({ size = 22, onClick }) {
  return (
    <button
      onClick={onClick}
      style={{
        display: "inline-flex",
        alignItems: "center",
        gap: 10,
        fontFamily: "var(--font-display)",
        fontSize: Math.max(15, size * 0.9),
        fontWeight: 600,
        letterSpacing: "-0.02em",
        color: "var(--fg)",
      }}
      aria-label="Gestopia — accueil"
    >
      <LogoMark size={size} />
      <span>Gestopia</span>
    </button>
  );
}

// ─────────────────────────────────────────────────────────────
// Nav — sticky, logo left + center links + right (Login + CTA).
// ─────────────────────────────────────────────────────────────
function Nav({ view, setView, goToInfo }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  // Each nav link is either a same-page anchor or an info-page route.
  // Order MUST match the on-page section flow so users can scan top→bottom.
  const navLinks = [
    { label: "Clients", kind: "anchor", target: "#clients" },           // 1st section after hero
    { label: "Fonctionnalités", kind: "anchor", target: "#features" },  // then features grid
    { label: "Produit", kind: "anchor", target: "#produit" },           // then "L'atelier en direct"
    { label: "Tarifs", kind: "anchor", target: "#tarifs" },             // then pricing
    { label: "Docs", kind: "info", target: "documentation" },           // → info page
  ];

  const onLinkClick = (e, l) => {
    if (l.kind === "info") {
      e.preventDefault();
      const go = goToInfo || window.__goToInfo;
      if (go) go(l.target);
    } else if (view !== "landing") {
      // We're not on landing — bounce to landing, then scroll once mounted.
      e.preventDefault();
      const anchor = l.target;
      setView("landing");
      setTimeout(() => {
        const el = document.querySelector(anchor);
        if (el) {
          const top = el.getBoundingClientRect().top + window.scrollY - 64;
          window.scrollTo({ top, behavior: "smooth" });
        }
      }, 80);
    }
    // else: default anchor behavior on landing
  };

  return (
    <header
      style={{
        position: "sticky",
        top: 0,
        zIndex: 50,
        background: scrolled
          ? "color-mix(in oklab, var(--bg) 78%, transparent)"
          : "transparent",
        backdropFilter: scrolled ? "blur(14px) saturate(140%)" : "none",
        WebkitBackdropFilter: scrolled ? "blur(14px) saturate(140%)" : "none",
        borderBottom: scrolled ? "1px solid var(--line)" : "1px solid transparent",
        transition: "all 220ms ease",
      }}
    >
      <div
        className="container"
        style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          height: 64,
        }}
      >
        <div style={{ display: "flex", alignItems: "center", gap: 32 }}>
          <Logo size={26} onClick={() => setView("landing")} />
        </div>

        <nav
          style={{
            display: "flex",
            alignItems: "center",
            gap: 28,
            fontSize: 13.5,
            color: "var(--fg-dim)",
          }}
        >
          {navLinks.map((l) => (
            <a
              key={l.label}
              href={l.kind === "anchor" ? l.target : "#"}
              onClick={(e) => onLinkClick(e, l)}
              className="ulink"
              style={{ color: "inherit" }}
            >
              {l.label}
            </a>
          ))}
        </nav>

        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <button
            onClick={() => setView("login")}
            className="btn btn-sm"
            style={{ color: "var(--fg-dim)" }}
          >
            Connexion
          </button>
          <button
            onClick={() => setView("signup")}
            className="btn btn-sm btn-primary"
          >
            Démarrer
            <span aria-hidden="true" style={{ fontFamily: "var(--font-mono)", fontSize: 13 }}>→</span>
          </button>
        </div>
      </div>
    </header>
  );
}

// ─────────────────────────────────────────────────────────────
// MockDashboard — a placeholder dashboard composed only of
// rectangles & lines. NOT the real product UI; gives a sense
// of density and structure.
// ─────────────────────────────────────────────────────────────
function MockDashboard({ height = 560 }) {
  return (
    <div
      className="grain"
      style={{
        position: "relative",
        width: "100%",
        height,
        background: "var(--surface)",
        border: "1px solid var(--line-strong)",
        borderRadius: 18,
        overflow: "hidden",
        boxShadow:
          "0 60px 120px -40px rgba(0,0,0,0.6), inset 0 0 0 1px rgba(255,255,255,0.02)",
      }}
    >
      {/* Window chrome */}
      <div
        style={{
          height: 38,
          borderBottom: "1px solid var(--line)",
          display: "flex",
          alignItems: "center",
          gap: 8,
          padding: "0 14px",
          background: "var(--bg-2)",
        }}
      >
        <span style={{ width: 10, height: 10, borderRadius: 999, background: "var(--line-strong)" }} />
        <span style={{ width: 10, height: 10, borderRadius: 999, background: "var(--line-strong)" }} />
        <span style={{ width: 10, height: 10, borderRadius: 999, background: "var(--line-strong)" }} />
        <div
          style={{
            marginLeft: 14,
            fontFamily: "var(--font-mono)",
            fontSize: 11,
            color: "var(--fg-faint)",
          }}
        >
          app.gestopia.fr / tableau de bord
        </div>
      </div>

      {/* Body */}
      <div style={{ display: "grid", gridTemplateColumns: "200px 1fr", height: "calc(100% - 38px)" }}>
        {/* Sidebar */}
        <aside
          style={{
            borderRight: "1px solid var(--line)",
            padding: "18px 14px",
            display: "flex",
            flexDirection: "column",
            gap: 4,
            background: "var(--bg-2)",
          }}
        >
          <div className="mono-eyebrow" style={{ marginBottom: 10 }}>BOUTIQUE</div>
          {[
            ["Tableau", true],
            ["Réparations", false],
            ["Clients", false],
            ["Stock & pièces", false],
            ["Devis & factures", false],
            ["Caisse", false],
            ["Étiquettes", false],
          ].map(([label, active]) => (
            <div
              key={label}
              style={{
                padding: "7px 10px",
                borderRadius: 6,
                background: active ? "var(--surface-2)" : "transparent",
                color: active ? "var(--fg)" : "var(--fg-dim)",
                fontSize: 12.5,
                display: "flex",
                alignItems: "center",
                gap: 8,
              }}
            >
              <span
                style={{
                  width: 5, height: 5, borderRadius: 999,
                  background: active ? "var(--accent)" : "var(--line-strong)",
                }}
              />
              {label}
            </div>
          ))}
        </aside>

        {/* Main */}
        <main style={{ padding: 20, display: "flex", flexDirection: "column", gap: 16, overflow: "hidden" }}>
          {/* KPI row */}
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12 }}>
            {[
              ["Tickets ouverts", "27", "+4"],
              ["CA du jour", "1 284 €", "+12%"],
              ["Pièces faibles", "6", "—"],
              ["Délai moyen", "1.8 j", "-0.3j"],
            ].map(([k, v, d], i) => (
              <div
                key={i}
                style={{
                  border: "1px solid var(--line)",
                  borderRadius: 12,
                  padding: 14,
                  background: "var(--surface-2)",
                }}
              >
                <div className="mono-eyebrow" style={{ fontSize: 10 }}>{k}</div>
                <div
                  style={{
                    marginTop: 6,
                    fontFamily: "var(--font-display)",
                    fontSize: 24,
                    fontWeight: 600,
                    letterSpacing: "-0.02em",
                  }}
                >
                  {v}
                </div>
                <div style={{ marginTop: 2, fontSize: 11, color: "var(--accent)" }}>{d}</div>
              </div>
            ))}
          </div>

          {/* Tickets table */}
          <div
            style={{
              flex: 1,
              border: "1px solid var(--line)",
              borderRadius: 12,
              overflow: "hidden",
              display: "flex",
              flexDirection: "column",
              background: "var(--surface-2)",
            }}
          >
            <div
              style={{
                padding: "12px 16px",
                borderBottom: "1px solid var(--line)",
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center",
              }}
            >
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <span className="mono-eyebrow" style={{ fontSize: 10 }}>FICHE RÉPA · LIVE</span>
                <span className="dash-pulse" style={{ width: 6, height: 6, borderRadius: 999, background: "var(--accent)" }} />
              </div>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--fg-faint)" }}>
                27 résultats
              </div>
            </div>
            <div style={{ display: "flex", flexDirection: "column" }}>
              {[
                ["#R-4821", "iPhone 13 — écran", "M. Bertrand", "En cours", "var(--accent)"],
                ["#R-4820", "Galaxy S22 — batterie", "L. Moreau", "Devis envoyé", "#FFD400"],
                ["#R-4819", "MacBook Air — clavier", "Atelier X", "Prêt", "#00E5A0"],
                ["#R-4818", "iPad Pro — vitre", "C. Robin", "Pièce attendue", "#4F8BFF"],
                ["#R-4817", "Pixel 8 — port USB", "A. Diop", "À diagnostiquer", "var(--fg-faint)"],
              ].map(([id, item, client, status, color], i) => (
                <div
                  key={i}
                  style={{
                    display: "grid",
                    gridTemplateColumns: "90px 1fr 1fr 140px 24px",
                    gap: 12,
                    alignItems: "center",
                    padding: "10px 16px",
                    borderTop: i === 0 ? "none" : "1px solid var(--line)",
                    fontSize: 13,
                  }}
                >
                  <div style={{ fontFamily: "var(--font-mono)", fontSize: 11.5, color: "var(--fg-dim)" }}>{id}</div>
                  <div>{item}</div>
                  <div style={{ color: "var(--fg-dim)" }}>{client}</div>
                  <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    <span style={{ width: 6, height: 6, borderRadius: 999, background: color }} />
                    <span style={{ fontSize: 12.5 }}>{status}</span>
                  </div>
                  <div style={{ color: "var(--fg-faint)", fontFamily: "var(--font-mono)", fontSize: 12 }}>›</div>
                </div>
              ))}
            </div>
          </div>
        </main>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Hero backdrop — clean architecture.
//
// SYSTEM:
//   The grid lives only in the upper portion of the hero (top 55%)
//   where the headline & ticket card sit. Below that the hero is
//   plain dark bg — so when the next section starts, there's nothing
//   to "fade" because both are already the same flat color.
//   No horizon, no decorative junk — the visual continuity is
//   structural, not a special effect.
// ─────────────────────────────────────────────────────────────
function HeroBackdrop({ variant = "motion" }) {
  if (variant === "mockup") return null;
  return (
    <div
      aria-hidden="true"
      style={{
        position: "absolute",
        inset: 0,
        overflow: "hidden",
        pointerEvents: "none",
        zIndex: 0,
      }}
    >
      {/* Corail wash — top right, anchored within the hero */}
      <div
        className="glow-pulse"
        style={{
          position: "absolute",
          left: "55%",
          top: "5%",
          width: "min(900px, 80vw)",
          height: "min(600px, 60vh)",
          background:
            "radial-gradient(ellipse at center, color-mix(in oklab, var(--accent) 38%, transparent), transparent 65%)",
          filter: "blur(30px)",
        }}
      />

      {/* Grid — top 55% only, with a smooth opacity fade at the bottom edge */}
      <svg
        width="100%"
        height="65%"
        style={{ position: "absolute", left: 0, top: 0 }}
        preserveAspectRatio="none"
      >
        <defs>
          <pattern id="grid" patternUnits="userSpaceOnUse" width="80" height="80">
            <path d="M 80 0 L 0 0 0 80" fill="none" stroke="currentColor" strokeWidth="0.5" />
          </pattern>
          <linearGradient id="grid-vfade" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="white" stopOpacity="0.7" />
            <stop offset="65%" stopColor="white" stopOpacity="0.6" />
            <stop offset="100%" stopColor="white" stopOpacity="0" />
          </linearGradient>
          <mask id="grid-mask">
            <rect width="100%" height="100%" fill="url(#grid-vfade)" />
          </mask>
        </defs>
        <rect
          width="100%"
          height="100%"
          fill="url(#grid)"
          style={{ color: "var(--line-strong)" }}
          mask="url(#grid-mask)"
        />
      </svg>
    </div>
  );
}

// Make available globally for other Babel scripts
Object.assign(window, { Logo, Nav, MockDashboard, HeroBackdrop });
