/* global React */
// Lexo AI — shared React building blocks. Exported to window for the other JSX files.
const { useState, useEffect, useRef, useContext, createContext, useCallback } = React;

// ── Brand mark ───────────────────────────────────────────────────────────────
const LEXO_MARK_PATH = "m 250,100 c -27.61424,0 -50,22.38576 -50,50 -1e-5,0.21922 -0.0176,0.45488 -0.0449,0.69727 a 50,50 0 0 1 -48.60547,49.21484 c -0.46755,0.0528 -0.92365,0.0878 -1.34961,0.0879 -27.61424,0 -50,22.38576 -50,50 0,27.61424 22.38576,50 50,50 a 50,50 0 0 1 49.9707,49.55078 C 199.99022,349.7087 200,349.85913 200,350 c 0,27.61424 22.38576,50 50,50 27.61424,0 50,-22.38576 50,-50 0,-27.61424 -22.38576,-50 -50,-50 -0.13264,-10e-6 -0.26758,-0.0111 -0.40234,-0.0273 A 50,50 0 0 1 200.04492,250.69922 C 200.01744,250.46641 200,250.23356 200,250 a 50,50 0 0 1 48.47656,-49.90039 c 0.53359,-0.0589 1.04796,-0.0996 1.52149,-0.0996 a 50,50 0 0 1 0.002,0 c 27.61424,0 50,-22.38576 50,-50 0,-27.61424 -22.38576,-50 -50,-50 z m 100,100 a 50,50 0 0 0 -50,50 50,50 0 0 0 50,50 50,50 0 0 0 50,-50 50,50 0 0 0 -50,-50 z";

function BrandMark({ size = 30 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 300 300" aria-hidden="true" style={{ display: "block" }}>
      <g transform="translate(-200,-100)">
        <path fill="currentColor" transform="translate(100)" d={LEXO_MARK_PATH} />
      </g>
    </svg>
  );
}

function Wordmark({ size }) {
  return (
    <span className="lx-wordmark" style={size ? { fontSize: size } : undefined}>
      Lexo<span>&nbsp;AI</span>
    </span>
  );
}

// ── Lucide icon ────────────────────────────────────────────────────────────
// React owns the wrapper <span>; Lucide draws an <svg> inside it. JSX gives the
// span no children, so React never diffs what Lucide injected — no removeChild
// crashes on re-render.
function Icon({ name, className = "", style }) {
  const ref = useRef(null);
  useEffect(() => {
    const host = ref.current;
    if (!host || !window.lucide) return;
    host.innerHTML = "";
    const i = document.createElement("i");
    i.setAttribute("data-lucide", name);
    host.appendChild(i);
    try { window.lucide.createIcons({ nameAttr: "data-lucide" }); } catch (e) {}
  }, [name]);
  return <span ref={ref} className={"lic " + className} style={style} aria-hidden="true" />;
}

// ── Button ───────────────────────────────────────────────────────────────────
function Button({ variant = "primary", size = "md", href, onClick, children, className = "", ...rest }) {
  const cls = `lx-btn lx-btn--${variant} lx-btn--${size} ${className}`.trim();
  if (href) return <a className={cls} href={href} onClick={onClick} {...rest}>{children}</a>;
  return <button className={cls} onClick={onClick} {...rest}>{children}</button>;
}

// ── Section head ─────────────────────────────────────────────────────────────
function Overline({ children }) {
  return <span className="t-overline lx-overline">{children}</span>;
}

function SectionHead({ overline, title, children, center }) {
  return (
    <div className={"lx-head reveal" + (center ? " center" : "")}>
      {overline && <Overline>{overline}</Overline>}
      <h2>{title}</h2>
      {children && <p>{children}</p>}
    </div>
  );
}

// ── Reveal-on-scroll wrapper ─────────────────────────────────────────────────
// Plain class hook; the App attaches one IntersectionObserver after each route
// render to add `.visible`.
function Reveal({ as: Tag = "div", className = "", children, ...rest }) {
  return <Tag className={("reveal " + className).trim()} {...rest}>{children}</Tag>;
}

// ── Demo modal context ───────────────────────────────────────────────────────
const DemoContext = createContext(() => {});
function useDemo() { return useContext(DemoContext); }

function DemoModal({ onClose }) {
  const [sent, setSent] = useState(false);
  const scrimRef = useRef(null);
  const [show, setShow] = useState(false);

  useEffect(() => {
    const r = requestAnimationFrame(() => setShow(true));
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    return () => { cancelAnimationFrame(r); document.removeEventListener("keydown", onKey); };
  }, [onClose]);

  return (
    <div ref={scrimRef} className={"lx-modal__scrim" + (show ? " show" : "")}
         onClick={(e) => { if (e.target === scrimRef.current) onClose(); }}>
      <div className="lx-modal" role="dialog" aria-modal="true" aria-labelledby="demoTitle">
        {!sent ? (
          <div>
            <div className="lx-modal__head">
              <div>
                <h3 id="demoTitle">Demander une démo</h3>
                <p className="lx-modal__sub">Découvrez Lexo AI en 30 minutes avec un expert. Réponse sous 24 h ouvrées.</p>
              </div>
              <button className="lx-modal__x" onClick={onClose} aria-label="Fermer"><Icon name="x" /></button>
            </div>
            <div className="lx-field"><label>Nom &amp; cabinet</label><input type="text" placeholder="Maître Dubois — Cabinet Dubois" /></div>
            <div className="lx-field"><label>E-mail professionnel</label><input type="email" placeholder="contact@cabinet-dubois.fr" /></div>
            <Button variant="primary" size="lg" onClick={() => setSent(true)}>Envoyer la demande</Button>
          </div>
        ) : (
          <div className="lx-modal__ok">
            <Icon name="circle-check" style={{ fontSize: 42 }} />
            <h3>Demande envoyée</h3>
            <p>Merci. Un conseiller Lexo AI vous recontacte très vite.</p>
            <Button variant="secondary" size="md" onClick={onClose}>Fermer</Button>
          </div>
        )}
      </div>
    </div>
  );
}

// ── Header ───────────────────────────────────────────────────────────────────
const NAV = [
  { id: "accueil", label: "Accueil", href: "#/" },
  { id: "services", label: "Services", href: "#/services" },
  { id: "apropos", label: "À propos", href: "#/a-propos" },
  { id: "contact", label: "Contact", href: "#/contact" },
];

function Header({ route }) {
  const openDemo = useDemo();
  const [scrolled, setScrolled] = useState(false);
  const [menu, setMenu] = useState(false);

  useEffect(() => {
    const on = () => setScrolled(window.scrollY > 12);
    on();
    window.addEventListener("scroll", on, { passive: true });
    return () => window.removeEventListener("scroll", on);
  }, []);
  useEffect(() => { setMenu(false); }, [route]);

  return (
    <>
      <header className={"lx-header" + (scrolled ? " scrolled" : "")}>
        <div className="lx-header__in">
          <a className="lx-brand" href="#/" aria-label="Lexo AI — accueil"><BrandMark size={30} /><Wordmark /></a>
          <nav className="lx-nav">
            {NAV.map((n) => (
              <a key={n.id} href={n.href} className={route === n.id ? "active" : undefined}>{n.label}</a>
            ))}
          </nav>
          <button className="lx-menu-btn" aria-label="Menu" onClick={() => setMenu((m) => !m)}>
            <Icon name={menu ? "x" : "menu"} />
          </button>
        </div>
      </header>
      <nav className={"lx-mobnav" + (menu ? " open" : "")}>
        {NAV.map((n) => (
          <a key={n.id} href={n.href} className={route === n.id ? "active" : undefined}>{n.label}</a>
        ))}
      </nav>
    </>
  );
}

// ── Footer ───────────────────────────────────────────────────────────────────
function Footer() {
  return (
    <footer className="lx-footer">
      <div className="lx-container">
        <div className="lx-footer__top">
          <div className="lx-footer__brand">
            <a className="lx-brand" href="#/"><BrandMark size={28} /><Wordmark size={20} /></a>
            <p>L'IA souveraine pour les professionnels du droit et de la finance. Conçue et hébergée en France, jamais entraînée sur vos données.</p>
          </div>
          <div className="lx-footer__cols">
            <div className="lx-footer__col">
              <h5>Produit</h5>
              <a href="#/services">Services</a><a href="#/services">Sécurité</a>
              <a href="#/services">Intégrations</a><a href="#/services">Chat juridique</a>
            </div>
            <div className="lx-footer__col">
              <h5>Cabinet</h5>
              <a href="#/a-propos">À propos</a><a href="#/a-propos">Nos valeurs</a>
              <a href="#/contact">Contact</a><a href="#/contact">Carrières</a>
            </div>
            <div className="lx-footer__col">
              <h5>Légal</h5>
              <a href="#/">RGPD</a><a href="#/">CGU</a><a href="#/">Mentions légales</a><a href="#/">Confidentialité</a>
            </div>
          </div>
        </div>
        <div className="lx-footer__bar">
          <span>© 2026 Lexo AI · Tous droits réservés.</span>
          <span>Hébergé en France · SecNumCloud · ISO 27001</span>
        </div>
      </div>
    </footer>
  );
}

// ── Inbox preview (home hero product shot) ───────────────────────────────────
function InboxPreview() {
  const openDemo = useDemo();
  return (
    <div className="lx-hero__shot reveal">
      <div className="lxp">
        <div className="lxp__bar">
          <span style={{ color: "var(--navy-700)", display: "inline-flex" }}><BrandMark size={16} /></span>
          <span className="lxp__title">Boîte de réception — Lexo AI</span>
          <span className="lxp__count">4 nouveaux</span>
        </div>
        {[
          { av: "MC", c: "var(--bordeaux-500)", n: "Marie Chartier", s: "Litige commercial — dossier #4821", t: "urgent", tl: "Urgent" },
          { av: "TD", c: "var(--navy-700)", n: "Thomas Dubois", s: "Suivi de notre rendez-vous du 12 mai", t: "client", tl: "Client" },
          { av: "GT", c: "var(--brass-600)", n: "Greffe — Tribunal", s: "Convocation — audience du 3 juin", t: "admin", tl: "Admin" },
          { av: "SE", c: "var(--slate-500)", n: "Sophie Evrard", s: "Veille jurisprudentielle — mai 2026", t: "info", tl: "Info" },
        ].map((r, i) => (
          <div className="lxp__row" key={i}>
            <span className="lxp__av" style={{ background: r.c }}>{r.av}</span>
            <span className="lxp__b"><b>{r.n}</b><i>{r.s}</i></span>
            <span className={"lxp__tag lxp__tag--" + r.t}>{r.tl}</span>
          </div>
        ))}
        <div className="lxp__reply">
          <div className="lxp__rh"><Icon name="sparkles" /> Réponse suggérée par Lexo AI</div>
          <p>Bonjour Madame Chartier, le dossier #4821 est <strong>en état d'être plaidé</strong> : conclusions déposées le 18 mai et pièces adverses intégrées. <strong>Aucune diligence n'est attendue de votre part</strong> avant l'audience du 3 juin.</p>
          <div className="lxp__ra"><span>Modifier</span><b>Valider &amp; envoyer</b></div>
        </div>
      </div>
      <div className="lxp-float lxp-float--r"><Icon name="scan-text" /> Analyse en temps réel</div>
      <div className="lxp-float lxp-float--l"><Icon name="folder-check" /> Pièce archivée au dossier</div>
    </div>
  );
}

// ── FAQ accordion ─────────────────────────────────────────────────────────────
function Faq({ items }) {
  const [open, setOpen] = useState(-1);
  // Manage reveal visibility in React so re-renders (open/close) don't clobber
  // the `visible` class the global IntersectionObserver would add imperatively.
  const wrapRef = React.useRef(null);
  const [visible, setVisible] = useState(false);
  React.useEffect(() => {
    const node = wrapRef.current;
    if (!node) return;
    if (document.body.classList.contains("no-reveal")) { setVisible(true); return; }
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { setVisible(true); io.disconnect(); } });
    }, { threshold: 0.1, rootMargin: "0px 0px -40px 0px" });
    io.observe(node);
    return () => io.disconnect();
  }, []);
  return (
    <div className="lx-faq" ref={wrapRef}>
      {items.map((it, i) => (
        <div key={i} className={"lx-faqitem reveal" + (visible ? " visible" : "") + (open === i ? " open" : "")}>
          <button className="lx-faqitem__q" onClick={() => setOpen(open === i ? -1 : i)}>
            {it.q}<Icon name="plus" />
          </button>
          <div className="lx-faqitem__a" style={{ maxHeight: open === i ? "500px" : "0px" }}>
            <p>{it.a}</p>
          </div>
        </div>
      ))}
    </div>
  );
}

// ── Final CTA band ────────────────────────────────────────────────────────────
function CtaBand({ title, children, secondaryHref, secondaryLabel, note }) {
  return (
    <section className="lx-cta">
      <div className="lx-container">
        <div className="lx-cta__box reveal">
          <h2>{title}</h2>
          <p>{children}</p>
          <div className="lx-cta__actions">
            <Button variant="accent" size="lg" href="#/contact">Nous contacter</Button>
            {secondaryHref && <Button variant="secondary" size="lg" href={secondaryHref}>{secondaryLabel}</Button>}
          </div>
          {note && (
            <div className="lx-cta__note">
              {note.map((n, i) => (<span key={i}><Icon name="check" />{n}</span>))}
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, {
  BrandMark, Wordmark, Icon, Button, Overline, SectionHead, Reveal,
  DemoContext, useDemo, DemoModal, Header, Footer, InboxPreview, Faq, CtaBand, NAV,
});
