// App shell - navigation + tweaks orchestration

const VARIANT_DESC = {
  schematic: { name: "Schematic Editorial", note: "Light | technical hairlines | editorial serif" },
  reactor:   { name: "Glass Reactor", note: "Premium | glassmorphism | cyan accents" },
  brutalist: { name: "Industrial Brutalist", note: "High contrast | mono | hard edges" },
};

const FONT_PRESETS = {
  default: null,
  inter:   { display: "Inter", body: "Inter", mono: "JetBrains Mono" },
  ibm:     { display: "IBM Plex Sans", body: "IBM Plex Sans", mono: "IBM Plex Mono" },
  archivo: { display: "Archivo", body: "Archivo", mono: "IBM Plex Mono" },
};

const PROTOTYPE_MODE = new URLSearchParams(window.location.search).get("prototype") === "1";
const EXPERTSTEAM_ROUTES = {
  "es-login": "/expertsteam/login",
  "es-hub": "/expertsteam/",
  "es-wizard": "/expertsteam/",
  "es-results": "/expertsteam/",
  "es-audit": "/expertsteam/audit",
  "es-guides": "/expertsteam/guides",
  "es-report": "/expertsteam/audit/report",
};

function App() {
  const [t, setTweak] = useTweaks(window.TWEAK_DEFAULTS);
  const [view, setView] = React.useState(PROTOTYPE_MODE ? (t.view || "landing") : "landing");

  React.useEffect(() => {
    const h = document.documentElement;
    h.dataset.variant = t.variant;
    h.dataset.theme = t.theme;
    h.dataset.density = t.density;
    h.dataset.cards = t.cards || "default";
    h.dataset.bgTone = t.bgTone || "warm";
  }, [t.variant, t.theme, t.density, t.cards, t.bgTone]);

  React.useEffect(() => {
    const h = document.documentElement;
    const p = FONT_PRESETS[t.font];
    if (!p) {
      h.style.removeProperty("--font-display");
      h.style.removeProperty("--font-body");
      h.style.removeProperty("--font-mono");
      return;
    }

    h.style.setProperty("--font-display", `'${p.display}', serif`);
    h.style.setProperty("--font-body", `'${p.body}', sans-serif`);
    h.style.setProperty("--font-mono", `'${p.mono}', monospace`);
  }, [t.font]);

  const openExpertSteam = React.useCallback((target = "es-login") => {
    const nextRoute = EXPERTSTEAM_ROUTES[target] || EXPERTSTEAM_ROUTES["es-login"];
    window.location.assign(nextRoute);
  }, []);

  const goTo = React.useCallback((nextView) => {
    if (!PROTOTYPE_MODE && nextView !== "landing") {
      openExpertSteam(nextView);
      return;
    }

    setView(nextView);
    setTweak("view", nextView);
    window.scrollTo({ top: 0 });
  }, [openExpertSteam, setTweak]);

  const switchVariant = (nextVariant) => {
    const defaultsByVariant = {
      schematic: { theme: "light", cards: "outline" },
      reactor: { theme: "dark", cards: "glass" },
      brutalist: { theme: "light", cards: "flat" },
    };
    setTweak({ variant: nextVariant, ...defaultsByVariant[nextVariant] });
  };

  let body = null;
  if (view === "landing") {
    body = (
      <Landing
        variant={t.variant}
        onCTA={(target) => {
          if (target === "expertsteam") {
            goTo("es-login");
            return;
          }

          if (target === "contact") {
            window.location.href = "/contacto/";
          }

          if (target === "diagnostico-agente-whatsapp") {
            window.location.href = "/diagnostico-agente-whatsapp/";
          }
        }}
      />
    );
  } else if (view === "es-login") {
    body = <ESLogin variant={t.variant} onLogin={() => goTo("es-hub")} />;
  } else if (view === "es-hub") {
    body = <ESHub variant={t.variant} onOpen={(id) => goTo(`es-${id}`)} />;
  } else if (view === "es-wizard") {
    body = <ESWizard variant={t.variant} onNext={() => goTo("es-results")} onBack={() => goTo("es-hub")} />;
  } else if (view === "es-results") {
    body = <ESResults variant={t.variant} onBack={() => goTo("es-wizard")} onPrint={() => goTo("es-report")} />;
  } else if (view === "es-audit") {
    body = <ESAudit variant={t.variant} onOpenTrap={() => goTo("es-results")} />;
  } else if (view === "es-guides") {
    body = <ESGuides variant={t.variant} />;
  } else if (view === "es-report") {
    body = <ESReport variant={t.variant} onBack={() => goTo("es-results")} />;
  }

  return (
    <div className="app-shell">
      <TopBar view={view} setView={goTo} variant={t.variant} prototypeMode={PROTOTYPE_MODE} />
      <div style={{ flex: 1 }}>{body}</div>

      {PROTOTYPE_MODE && (
        <TweaksPanel title="Tweaks | Design">
          <TweakSection label="Visual direction" />
          <TweakRadio
            label="Variant"
            value={t.variant}
            options={[
              { label: "Schem.", value: "schematic" },
              { label: "React.", value: "reactor" },
              { label: "Brut.", value: "brutalist" },
            ]}
            onChange={switchVariant}
          />
          <div style={{ padding: "6px 10px", background: "rgba(0,0,0,.05)", borderRadius: 8, fontSize: 10.5, lineHeight: 1.4, color: "rgba(41,38,27,.72)" }}>
            <b>{VARIANT_DESC[t.variant].name}</b><br />
            <span style={{ color: "rgba(41,38,27,.55)" }}>{VARIANT_DESC[t.variant].note}</span>
          </div>

          <TweakSection label="Theme" />
          <TweakRadio
            label="Mode"
            value={t.theme}
            options={[{ label: "Light", value: "light" }, { label: "Dark", value: "dark" }]}
            onChange={(value) => setTweak("theme", value)}
          />

          <TweakSection label="Background" />
          <TweakSelect
            label="Tone"
            value={t.bgTone || "warm"}
            options={[
              { label: "Warm beige", value: "warm" },
              { label: "Soft off-white", value: "off" },
              { label: "Pure white", value: "white" },
              { label: "Cool blue-gray", value: "cool" },
              { label: "Blueprint", value: "blueprint" },
            ]}
            onChange={(value) => setTweak("bgTone", value)}
          />

          <TweakSection label="Cards" />
          <TweakSelect
            label="Style"
            value={t.cards}
            options={[
              { label: "Outline", value: "outline" },
              { label: "Flat", value: "flat" },
              { label: "Glass", value: "glass" },
            ]}
            onChange={(value) => setTweak("cards", value)}
          />

          <TweakSection label="Density" />
          <TweakRadio
            label="Spacing"
            value={t.density}
            options={[
              { label: "Comp.", value: "compact" },
              { label: "Reg.", value: "regular" },
              { label: "Comfy", value: "comfy" },
            ]}
            onChange={(value) => setTweak("density", value)}
          />

          <TweakSection label="Typography" />
          <TweakSelect
            label="Fonts"
            value={t.font || "default"}
            options={[
              { label: "Auto by variant", value: "default" },
              { label: "Inter + JetBrains", value: "inter" },
              { label: "IBM Plex Sans + Mono", value: "ibm" },
              { label: "Archivo + IBM Plex Mono", value: "archivo" },
            ]}
            onChange={(value) => setTweak("font", value)}
          />

          <TweakSection label="Quick nav" />
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6 }}>
            <TweakButton label="Landing" onClick={() => goTo("landing")} secondary={view !== "landing"} />
            <TweakButton label="Login" onClick={() => goTo("es-login")} secondary={view !== "es-login"} />
            <TweakButton label="Hub" onClick={() => goTo("es-hub")} secondary={view !== "es-hub"} />
            <TweakButton label="Wizard" onClick={() => goTo("es-wizard")} secondary={view !== "es-wizard"} />
            <TweakButton label="Results" onClick={() => goTo("es-results")} secondary={view !== "es-results"} />
            <TweakButton label="Audit" onClick={() => goTo("es-audit")} secondary={view !== "es-audit"} />
            <TweakButton label="Guides" onClick={() => goTo("es-guides")} secondary={view !== "es-guides"} />
            <TweakButton label="Report" onClick={() => goTo("es-report")} secondary={view !== "es-report"} />
          </div>
        </TweaksPanel>
      )}
    </div>
  );
}

function TopBar({ view, setView, variant, prototypeMode }) {
  const [menuOpen, setMenuOpen] = React.useState(false);
  const onLanding = view === "landing";
  const inApp = view.startsWith("es-");
  const showSubnav = prototypeMode && inApp && view !== "es-login";

  const navItems = [
    { id: "es-hub", label: "Hub" },
    { id: "es-wizard", label: "Diagnostico" },
    { id: "es-audit", label: "Auditoria" },
    { id: "es-guides", label: "Guias" },
  ];
  const whatsappHref = "https://wa.me/573153251082?text=Hola%20CEIA%2C%20quiero%20solicitar%20un%20diagn%C3%B3stico%20comercial.";

  const landingLinks = [
    { label: "WEB\u00a0COMERCIAL", href: "/arquitectura-web-comercial/" },
    { label: "IA/WHATSAPP", href: "/agentes-ia-whatsapp/" },
    { label: "AUTOMATIZACIÓN", href: "/automatizacion-de-procesos/" },
    { label: "INGENIERÍA", href: "/ingenieria-industrial-eficiencia-energetica/" },
    { label: "CONTACTO", href: "/contacto/" },
  ];

  const scrollTo = (id) => {
    document.getElementById(id)?.scrollIntoView({ behavior: "smooth", block: "start" });
    setMenuOpen(false);
  };

  const radius = variant === "brutalist" ? 0 : 6;

  return (
    <>
    <header className="hd no-print" data-screen-label={onLanding ? "Top bar landing" : "Top bar app"}>
      <div
        style={{
          height: variant === "brutalist" ? 4 : 2,
          background: variant === "reactor"
            ? "linear-gradient(90deg, var(--accent) 0%, var(--accent-2) 100%)"
            : "var(--accent)",
        }}
      />

      <div className="hd-inner">
        <button
          onClick={() => { setView("landing"); setMenuOpen(false); }}
          style={{
            background: "none",
            border: 0,
            padding: 0,
            cursor: "pointer",
            display: "inline-flex",
            alignItems: "center",
            gap: 12,
            color: "var(--fg)",
          }}
        >
          <img src="assets/ceia-mark.png" alt="CEIA" width={36} height={36} style={{ display: "block", flexShrink: 0 }} />
          <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-start", lineHeight: 1.1, minWidth: 0 }}>
            <span className="display" style={{ fontSize: 17, fontWeight: 600, letterSpacing: "-.02em", whiteSpace: "nowrap", color: "var(--fg)", display: "inline-flex", alignItems: "baseline", gap: 5 }}>
              <span style={{ display: "inline-flex", alignItems: "baseline", letterSpacing: "-.055em" }}>
                CE<span style={{ fontSize: "1.24em", lineHeight: .86, marginLeft: 1, color: "#1B5E99", textShadow: "0 0 18px rgba(76,191,255,.22)" }}>IA</span>
              </span>
              <em style={{ fontStyle: variant === "schematic" ? "italic" : "normal", color: "var(--accent)", fontWeight: 500 }}>
                Ingenieria
              </em>
            </span>
            <span className="mono hd-tagline" style={{ fontSize: 9, color: "var(--fg-soft)", letterSpacing: ".22em", textTransform: "uppercase", marginTop: 3, whiteSpace: "nowrap" }}>
              {inApp ? "ExpertSteam | v1.0" : "Web comercial | IA | Automatizacion | Ingenieria"}
            </span>
          </div>
        </button>

        <div style={{ flex: 1 }} />

        {onLanding && (
          <>
            {/* Desktop nav links — hidden on mobile via CSS */}
            <nav className="hd-nav-links" style={{ display: "flex", gap: "var(--gap-3)", alignItems: "center" }}>
              {landingLinks.map((item) => (
                <a
                  key={item.label}
                  href={item.href || `#${item.id}`}
                  onClick={(event) => {
                    if (item.id) {
                      event.preventDefault();
                      scrollTo(item.id);
                    }
                  }}
                  className="link-anim mono"
                  style={{
                    fontSize: 11,
                    letterSpacing: ".14em",
                    textTransform: "uppercase",
                    color: "var(--fg-muted)",
                    textDecoration: "none",
                    cursor: "pointer",
                    whiteSpace: "nowrap",
                  }}
                >
                  {item.label}
                </a>
              ))}
            </nav>

            <a className="btn btn-primary hd-nav-links" href="/contacto/" style={{ whiteSpace: "nowrap", textDecoration: "none" }}>
              Solicitar diagnóstico comercial <IconArrowRight size={14} />
            </a>

            {/* Hamburger button — visible only on mobile via CSS */}
            <button
              className="hd-hamburger"
              onClick={() => setMenuOpen(!menuOpen)}
              aria-label={menuOpen ? "Cerrar menú" : "Abrir menú"}
              style={{
                background: "none",
                border: "none",
                borderRadius: 0,
                cursor: "pointer",
                padding: "4px 8px",
                display: "none",
                alignItems: "center",
                justifyContent: "center",
                color: "var(--fg-muted)",
                fontSize: 22,
                lineHeight: 1,
              }}
            >
              {menuOpen ? "✕" : "☰"}
            </button>
          </>
        )}

        {showSubnav && (
          <nav style={{ display: "flex", gap: 4, alignItems: "center", flexWrap: "wrap", justifyContent: "flex-end" }}>
            {navItems.map((item) => {
              const isActive = view === item.id;
              return (
                <button
                  key={item.id}
                  onClick={() => setView(item.id)}
                  className="mono"
                  style={{
                    padding: "8px 12px",
                    fontSize: 11,
                    letterSpacing: ".10em",
                    textTransform: "uppercase",
                    background: isActive ? "var(--accent-soft)" : "transparent",
                    color: isActive ? "var(--accent)" : "var(--fg-muted)",
                    border: "1px solid",
                    borderColor: isActive ? "color-mix(in oklch, var(--accent) 30%, transparent)" : "transparent",
                    borderRadius: radius,
                    cursor: "pointer",
                    transition: "all .15s",
                    fontWeight: isActive ? 600 : 500,
                    whiteSpace: "nowrap",
                  }}
                >
                  {item.label}
                </button>
              );
            })}
            <span style={{ width: 1, height: 20, background: "var(--line)", marginInline: 8 }} />
            <button
              onClick={() => setView("landing")}
              className="mono"
              style={{
                padding: "8px 12px",
                fontSize: 11,
                letterSpacing: ".12em",
                textTransform: "uppercase",
                background: "transparent",
                color: "var(--fg-muted)",
                border: "1px solid var(--line)",
                borderRadius: radius,
                cursor: "pointer",
                display: "inline-flex",
                alignItems: "center",
                gap: 6,
              }}
            >
              <IconLogout size={12} /> Salir
            </button>
          </nav>
        )}
      </div>

      {/* Mobile dropdown menu */}
      {onLanding && menuOpen && (
        <nav style={{
          borderTop: "1px solid var(--line-soft)",
          background: "var(--bg-elev)",
          padding: "var(--gap-3) var(--pad-4)",
          display: "flex",
          flexDirection: "column",
          gap: "var(--gap-2)",
        }}>
          {landingLinks.map((item) => (
            <a
              key={item.label}
              href={item.href || `#${item.id}`}
              onClick={(event) => {
                if (item.id) {
                  event.preventDefault();
                  scrollTo(item.id);
                } else {
                  setMenuOpen(false);
                }
              }}
              className="mono"
              style={{
                fontSize: 13,
                letterSpacing: ".12em",
                textTransform: "uppercase",
                color: "var(--fg-muted)",
                textDecoration: "none",
                padding: "10px 0",
                borderBottom: "1px solid var(--line-soft)",
                cursor: "pointer",
              }}
            >
              {item.label}
            </a>
          ))}
          <a
            className="btn btn-primary"
            href="/contacto/"
            onClick={() => { setMenuOpen(false); }}
            style={{ alignSelf: "flex-start", textDecoration: "none" }}
          >
            Solicitar diagnóstico comercial <IconArrowRight size={14} />
          </a>
        </nav>
      )}
    </header>
    {onLanding && (
      <a className="global-whatsapp-cta no-print" href={whatsappHref} target="_blank" rel="noopener" aria-label="Hablar con CEIA por WhatsApp">
        <span className="global-whatsapp-icon"><IconWhatsApp size={18} /></span>
        <span className="global-whatsapp-copy"><strong>Hablar por WhatsApp</strong><span>Diagnóstico comercial</span></span>
      </a>
    )}
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
