// ui.jsx — shared UI primitives for NOVA Résidence
// Loaded BEFORE app.jsx so its components and styles are available.

// ──────────────────────────────────────────────────────────────────────────
// PLACEHOLDER (striped image stand-in)
// ──────────────────────────────────────────────────────────────────────────

function Placeholder({ label, ratio = "16/9", tone = "warm", radius = 0, style = {}, children, src }) {
  const theme = window.useTheme ? window.useTheme() : null;
  const showLabel = theme ? theme.t.showPlaceholderLabels : true;
  const accent = theme ? theme.palette.accent : "#C5A572";
  const ink = theme ? theme.palette.ink : "#1F2A33";
  const bg = tone === "dark"
    ? (theme ? theme.palette.deep : "#1F2A33")
    : tone === "ink"
    ? ink
    : (theme ? theme.palette.bg2 : "#EBE6DA");

  const stripeColor = tone === "dark" || tone === "ink"
    ? "rgba(255,255,255,0.06)"
    : "rgba(31,42,51,0.06)";

  // If a real image src is provided, render it; placeholder label only shown if no src OR theme.showPlaceholderLabels is true AND we want overlay.
  return (
    <div
      className="nv-placeholder"
      style={{
        position: "relative",
        aspectRatio: ratio,
        background: bg,
        borderRadius: radius,
        overflow: "hidden",
        backgroundImage: src ? undefined : `repeating-linear-gradient(135deg, ${stripeColor} 0 1px, transparent 1px 14px)`,
        color: tone === "dark" || tone === "ink" ? "#F5F2EC" : ink,
        ...style,
      }}
    >
      {src && (
        <img src={src} alt={label || ""} style={{
          position: "absolute", inset: 0, width: "100%", height: "100%",
          objectFit: "cover", display: "block",
        }} />
      )}
      {!src && showLabel && (
        <div style={{
          position: "absolute", inset: 0,
          display: "flex", alignItems: "center", justifyContent: "center",
          flexDirection: "column", gap: 6,
          fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace",
          fontSize: 11, letterSpacing: "0.08em", textTransform: "uppercase",
          opacity: 0.65, textAlign: "center", padding: 24,
        }}>
          <span style={{
            width: 28, height: 28, borderRadius: "50%",
            border: `1px solid currentColor`, opacity: 0.5,
            display: "flex", alignItems: "center", justifyContent: "center",
            fontSize: 14,
          }}>◇</span>
          <span>{label || "image"}</span>
        </div>
      )}
      {children}
    </div>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// LOGO — wordmark + monogram (text-based since no logo file provided yet)
// ──────────────────────────────────────────────────────────────────────────

function Logo({ size = 32, variant = "full", dark = false, onClick }) {
  // Use the horizontal brand mark when full, the round monogram when compact
  const src = variant === "mark"
    ? (dark ? "assets/logo-mono-dore.png" : "assets/logo-rond.png")
    : (dark ? "assets/logo-fond-sombre.png" : "assets/logo-horizontal.png");
  const h = variant === "mark" ? size : Math.round(size * 1.05);
  return (
    <a href="#/accueil" onClick={(e) => { if (onClick) { e.preventDefault(); onClick(); } }}
       style={{ display: "inline-flex", alignItems: "center", textDecoration: "none" }}>
      <img src={src} alt="NOVA Résidence" style={{ height: h, width: "auto", display: "block" }} />
    </a>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// BUTTONS
// ──────────────────────────────────────────────────────────────────────────

function Button({ children, variant = "primary", onClick, href, size = "md", icon, style = {} }) {
  const sizing = size === "lg"
    ? { padding: "16px 28px", fontSize: 14 }
    : size === "sm"
    ? { padding: "8px 14px", fontSize: 12 }
    : { padding: "12px 22px", fontSize: 13 };

  const variantStyle = variant === "primary"
    ? { background: "var(--accent)", color: "#FAF6EC", border: "1px solid var(--accent)" }
    : variant === "dark"
    ? { background: "var(--ink)", color: "var(--bg)", border: "1px solid var(--ink)" }
    : variant === "ghost"
    ? { background: "transparent", color: "var(--ink)", border: "1px solid var(--line)" }
    : variant === "link"
    ? { background: "transparent", color: "var(--ink)", border: 0, padding: 0, textDecoration: "underline", textUnderlineOffset: 4 }
    : {};

  const Tag = href ? "a" : "button";
  return (
    <Tag
      href={href}
      onClick={onClick}
      style={{
        display: "inline-flex", alignItems: "center", gap: 10,
        fontFamily: "var(--font-b)", fontWeight: 500,
        letterSpacing: "0.04em", textTransform: "uppercase",
        cursor: "pointer", textDecoration: "none",
        borderRadius: 0, transition: "all .2s ease",
        ...sizing, ...variantStyle, ...style,
      }}
      onMouseEnter={(e) => { if (variant === "primary") e.currentTarget.style.background = "var(--accent-dark)"; }}
      onMouseLeave={(e) => { if (variant === "primary") e.currentTarget.style.background = "var(--accent)"; }}
    >
      <span>{children}</span>
      {icon && <span style={{ fontSize: "1.1em" }}>{icon}</span>}
    </Tag>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// SECTION SHELL
// ──────────────────────────────────────────────────────────────────────────

function Section({ children, bg = "bg", id, style = {}, fullBleed = false, label }) {
  return (
    <section id={id} style={{
      background: bg === "bg2" ? "var(--bg2)" : bg === "surface" ? "var(--surface)" : bg === "deep" ? "var(--deep)" : bg === "ink" ? "var(--ink)" : "var(--bg)",
      color: bg === "deep" || bg === "ink" ? "var(--bg)" : "var(--ink)",
      paddingTop: "var(--section-py)", paddingBottom: "var(--section-py)",
      ...style,
    }}>
      <div style={{
        maxWidth: fullBleed ? "100%" : 1280,
        margin: "0 auto", padding: fullBleed ? 0 : "0 48px",
      }}>
        {label && <Eyebrow>{label}</Eyebrow>}
        {children}
      </div>
    </section>
  );
}

function Eyebrow({ children, style = {} }) {
  return (
    <div style={{
      fontFamily: "var(--font-b)", fontSize: 11, fontWeight: 500,
      letterSpacing: "0.24em", textTransform: "uppercase",
      color: "var(--accent)", marginBottom: 24,
      display: "flex", alignItems: "center", gap: 12,
      ...style,
    }}>
      <span style={{ width: 24, height: 1, background: "var(--accent)" }}></span>
      {children}
    </div>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// TOP BAR
// ──────────────────────────────────────────────────────────────────────────

function TopBar({ route, navigate }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const links = [
    { id: "residence", label: "La Résidence" },
    { id: "appartements", label: "Appartements" },
    { id: "orange", label: "Orange" },
    { id: "investir", label: "Investir" },
    { id: "contact", label: "Contact" },
  ];

  return (
    <header style={{
      position: "sticky", top: 0, zIndex: 50,
      background: scrolled ? "color-mix(in srgb, var(--bg) 92%, 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: "background .25s ease, border-color .25s ease",
    }}>
      <div style={{
        maxWidth: 1280, margin: "0 auto",
        padding: "16px 48px",
        display: "flex", alignItems: "center", justifyContent: "space-between",
      }}>
        <Logo size={44} onClick={() => navigate("accueil")} />
        <nav style={{ display: "flex", alignItems: "center", gap: 32 }}>
          {links.map((l) => (
            <a key={l.id}
               href={`#/${l.id}`}
               onClick={(e) => { e.preventDefault(); navigate(l.id); }}
               style={{
                 fontFamily: "var(--font-b)", fontSize: 13,
                 color: route === l.id ? "var(--accent)" : "var(--ink)",
                 textDecoration: "none", fontWeight: 500,
                 letterSpacing: "0.02em",
                 paddingBottom: 3,
                 borderBottom: route === l.id ? "1px solid var(--accent)" : "1px solid transparent",
               }}>
              {l.label}
            </a>
          ))}
        </nav>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <a href="tel:+33766461865" style={{ fontFamily: "var(--font-b)", fontSize: 13, color: "var(--ink2)", textDecoration: "none" }}>07 66 46 18 65</a>
          <Button variant="dark" size="sm" onClick={() => navigate("contact")}>Prendre RDV</Button>
        </div>
      </div>
    </header>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// FOOTER
// ──────────────────────────────────────────────────────────────────────────

function Footer({ navigate }) {
  return (
    <footer style={{ background: "var(--ink)", color: "var(--bg)", paddingTop: 80, paddingBottom: 32 }}>
      <div style={{ maxWidth: 1280, margin: "0 auto", padding: "0 48px" }}>
        <div style={{
          display: "grid", gridTemplateColumns: "1.4fr 1fr 1fr 1fr",
          gap: 48, paddingBottom: 64, borderBottom: "1px solid rgba(255,255,255,.12)",
        }}>
          <div>
            <Logo size={56} dark />
            <p style={{ marginTop: 24, fontFamily: "var(--font-b)", fontSize: 14, lineHeight: 1.7, color: "rgba(242,235,221,.7)", maxWidth: 320 }}>
              Une petite résidence de huit T2 au cœur d'Orange, pensée pour vivre ou investir au soleil du Vaucluse.
            </p>
          </div>
          <FooterCol title="Le programme" links={[
            ["La Résidence", "residence"],
            ["Les Appartements", "appartements"],
            ["Plans & typologies", "appartements"],
          ]} navigate={navigate} />
          <FooterCol title="Acheter" links={[
            ["Investir", "investir"],
            ["Simulateur", "investir"],
            ["Orange & le quartier", "orange"],
          ]} navigate={navigate} />
          <div>
            <h4 style={{ fontFamily: "var(--font-b)", fontSize: 12, letterSpacing: "0.18em", textTransform: "uppercase", color: "rgba(242,235,221,.5)", fontWeight: 500, marginBottom: 20 }}>Contact</h4>
            <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 12 }}>
              <li style={{ fontFamily: "var(--font-b)", fontSize: 14, color: "var(--bg)" }}>Anne Magnoni</li>
              <li style={{ fontFamily: "var(--font-b)", fontSize: 14, color: "var(--bg)" }}><a href="tel:+33766461865" style={{ color: "inherit", textDecoration: "none" }}>07 66 46 18 65</a></li>
              <li style={{ fontFamily: "var(--font-b)", fontSize: 14, color: "var(--bg)" }}><a href="mailto:a.magnoni@myamo.com" style={{ color: "inherit", textDecoration: "none" }}>a.magnoni@myamo.com</a></li>
              <li style={{ fontFamily: "var(--font-b)", fontSize: 14, color: "rgba(242,235,221,.7)", lineHeight: 1.6 }}>Myamo Développement<br/>4-6 Place de la République<br/>13200 Arles</li>
            </ul>
          </div>
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 32, fontFamily: "var(--font-b)", fontSize: 12, color: "rgba(242,235,221,.5)" }}>
          <span>© {new Date().getFullYear()} NOVA Résidence — Myamo Développement — Tous droits réservés</span>
          <div style={{ display: "flex", gap: 24 }}>
            <a href="#" style={{ color: "inherit", textDecoration: "none" }}>Mentions légales</a>
            <a href="#" style={{ color: "inherit", textDecoration: "none" }}>RGPD</a>
            <a href="#" style={{ color: "inherit", textDecoration: "none" }}>Plaquette PDF</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

function FooterCol({ title, links, navigate }) {
  return (
    <div>
      <h4 style={{ fontFamily: "var(--font-b)", fontSize: 12, letterSpacing: "0.18em", textTransform: "uppercase", color: "rgba(242,235,221,.5)", fontWeight: 500, marginBottom: 20 }}>{title}</h4>
      <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 12 }}>
        {links.map(([label, route]) => (
          <li key={label}>
            <a href={`#/${route}`} onClick={(e) => { e.preventDefault(); navigate(route); }}
               style={{ fontFamily: "var(--font-b)", fontSize: 14, color: "rgba(242,235,221,.85)", textDecoration: "none" }}>
              {label}
            </a>
          </li>
        ))}
      </ul>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// FORMAT HELPERS
// ──────────────────────────────────────────────────────────────────────────

const fmtPrice = (n) => new Intl.NumberFormat("fr-FR", { style: "currency", currency: "EUR", maximumFractionDigits: 0 }).format(n);
const fmtN = (n) => new Intl.NumberFormat("fr-FR").format(Math.round(n));

// expose
Object.assign(window, {
  Placeholder, Logo, Button, Section, Eyebrow,
  TopBar, Footer, FooterCol, fmtPrice, fmtN,
});
