// ============================================================
// NAV — top bar + mobile menu + Viewing Preferences panel
// ============================================================

function ShardLogo({ size = 28 }) {
  const theme = window.useActiveTheme();
  const accent = theme.accent;
  return (
    <svg width={size} height={size * 1.4} viewBox="0 0 200 280" aria-hidden>
      <polygon
        points="100,10 180,160 100,260 30,140"
        fill={theme.accentSoft}
        stroke={accent}
        strokeWidth="6"
        strokeLinejoin="round"
      />
      <path
        d="M100 10 L100 260"
        stroke={accent}
        strokeWidth="4"
        strokeLinecap="round"
      />
      <path
        d="M30 140 L100 100 L180 160"
        stroke={accent}
        strokeWidth="4"
        strokeLinecap="round"
        fill="none"
      />
    </svg>
  );
}

function Nav() {
  const theme = window.useActiveTheme();
  const { isMobile } = window.useViewport();
  const [prefs] = window.usePrefs();
  const [menuOpen, setMenuOpen] = React.useState(false);
  const [prefsOpen, setPrefsOpen] = React.useState(false);

  const links = [
    { label: "Features", href: "/#features", key: "features" },
    { label: "How it works", href: "/#how", key: "how" },
    { label: "Use cases", href: "/#personas", key: "personas" },
    { label: "Pricing", href: "/#pricing", key: "pricing" },
    { label: "About", href: "/about", key: "about" },
    { label: "Contact", href: "/contact", key: "contact" },
  ];

  const navBgDark = "linear-gradient(to bottom, rgba(6,9,18,0.78), rgba(6,9,18,0))";
  const navBgLight = "linear-gradient(to bottom, rgba(246,241,226,0.78), rgba(246,241,226,0))";

  return (
    <React.Fragment>
      <nav
        style={{
          position: "fixed",
          top: 0,
          left: 0,
          right: 0,
          zIndex: 50,
          background: theme.dark ? navBgDark : navBgLight,
          backdropFilter: "blur(12px) saturate(140%)",
          WebkitBackdropFilter: "blur(12px) saturate(140%)",
          padding: isMobile ? "14px 20px" : "18px 40px",
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          fontSize: 14,
          color: theme.ink,
          fontFamily: "'DM Sans', sans-serif",
        }}
      >
        <a
          href="/"
          style={{
            display: "flex",
            alignItems: "center",
            gap: isMobile ? 10 : 12,
            textDecoration: "none",
            color: "inherit",
          }}
        >
          <ShardLogo size={isMobile ? 22 : 26} />
          <span
            style={{
              fontFamily: "'Lexend', sans-serif",
              fontWeight: 600,
              fontSize: isMobile ? 18 : 20,
              letterSpacing: -0.4,
            }}
          >
            Shard
          </span>
        </a>

        {!isMobile && (
          <div style={{ display: "flex", alignItems: "center", gap: 26 }}>
            {links.map((l) => (
              <a
                key={l.key}
                href={l.href}
                style={{
                  color: theme.sub,
                  textDecoration: "none",
                  fontSize: 14,
                  fontWeight: 500,
                  whiteSpace: "nowrap",
                  transition: "color 200ms",
                }}
                onMouseEnter={(e) => (e.currentTarget.style.color = theme.ink)}
                onMouseLeave={(e) => (e.currentTarget.style.color = theme.sub)}
              >
                {l.label}
              </a>
            ))}
          </div>
        )}

        <div style={{ display: "flex", alignItems: "center", gap: isMobile ? 8 : 12 }}>
          {!isMobile && (
            <a
              href="/contact?subject=demo"
              style={{
                padding: "10px 18px",
                borderRadius: 999,
                background: theme.accent,
                color: theme.onAccent,
                fontSize: 14,
                fontWeight: 600,
                textDecoration: "none",
                whiteSpace: "nowrap",
                boxShadow: theme.dark
                  ? `0 8px 26px -10px ${theme.accent}aa`
                  : "0 8px 26px -10px rgba(22,26,43,0.35)",
              }}
            >
              Get started
            </a>
          )}

          {/* Viewing Preferences trigger */}
          <button
            onClick={() => setPrefsOpen(!prefsOpen)}
            aria-expanded={prefsOpen}
            aria-label="Viewing Preferences"
            style={{
              display: "inline-flex",
              alignItems: "center",
              gap: 8,
              padding: isMobile ? "9px 10px" : "9px 14px",
              borderRadius: 999,
              background: prefsOpen ? theme.accent : "transparent",
              border: `1px solid ${prefsOpen ? theme.accent : theme.chipBorder}`,
              color: prefsOpen ? theme.onAccent : theme.ink,
              fontSize: 13,
              fontWeight: 500,
              cursor: "pointer",
              fontFamily: "inherit",
              transition: "all 200ms",
            }}
          >
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
              <circle cx="12" cy="12" r="5" stroke="currentColor" strokeWidth="2" />
              <path
                d="M12 2v3M12 19v3M2 12h3M19 12h3M4.5 4.5l2 2M17.5 17.5l2 2M4.5 19.5l2-2M17.5 6.5l2-2"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
              />
            </svg>
            {!isMobile && "Viewing Preferences"}
          </button>

          {isMobile && (
            <button
              onClick={() => setMenuOpen(!menuOpen)}
              aria-label="Menu"
              aria-expanded={menuOpen}
              style={{
                width: 40,
                height: 40,
                padding: 0,
                display: "inline-flex",
                alignItems: "center",
                justifyContent: "center",
                borderRadius: 999,
                background: menuOpen ? theme.accent : "transparent",
                border: `1px solid ${menuOpen ? theme.accent : theme.chipBorder}`,
                color: menuOpen ? theme.onAccent : theme.ink,
                cursor: "pointer",
                fontFamily: "inherit",
                transition: "all 200ms",
              }}
            >
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
                {menuOpen ? (
                  <path d="M6 6l12 12M6 18L18 6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
                ) : (
                  <path d="M4 7h16M4 12h16M4 17h16" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
                )}
              </svg>
            </button>
          )}
        </div>
      </nav>

      {isMobile && menuOpen && (
        <div
          style={{
            position: "fixed",
            top: 64,
            left: 12,
            right: 12,
            zIndex: 49,
            background: theme.surface,
            border: `1px solid ${theme.cardBorder}`,
            borderRadius: 16,
            padding: "12px 8px",
            boxShadow: theme.dark
              ? "0 30px 60px -20px rgba(0,0,0,0.6)"
              : "0 30px 60px -20px rgba(0,0,0,0.2)",
            fontFamily: "'DM Sans', sans-serif",
          }}
        >
          {links.map((l) => (
            <a
              key={l.key}
              href={l.href}
              onClick={() => setMenuOpen(false)}
              style={{
                display: "block",
                padding: "14px 16px",
                color: theme.sub,
                textDecoration: "none",
                fontSize: 16,
                fontWeight: 500,
                borderRadius: 10,
              }}
            >
              {l.label}
            </a>
          ))}
          <a
            href="/contact?subject=demo"
            onClick={() => setMenuOpen(false)}
            style={{
              display: "block",
              margin: "8px 8px 4px",
              padding: "14px 16px",
              borderRadius: 10,
              background: theme.accent,
              color: theme.onAccent,
              fontSize: 16,
              fontWeight: 600,
              textDecoration: "none",
              textAlign: "center",
            }}
          >
            Get started
          </a>
        </div>
      )}

      <ViewingPreferencesPanel open={prefsOpen} onClose={() => setPrefsOpen(false)} />
    </React.Fragment>
  );
}

// ============================================================
// VIEWING PREFERENCES PANEL — Theme · Text size · Line spacing ·
// Dyslexia-friendly mode. Same controls as BRAINS, same persistence.
// ============================================================

function ViewingPreferencesPanel({ open, onClose }) {
  const theme = window.useActiveTheme();
  const [prefs, setPrefs] = window.usePrefs();
  const { isMobile } = window.useViewport();

  // One-time: inject the Atkinson Hyperlegible font + dyslexia + line-spacing CSS.
  React.useEffect(() => {
    if (!document.getElementById("shard-dyslexia-font-link")) {
      const link = document.createElement("link");
      link.id = "shard-dyslexia-font-link";
      link.rel = "stylesheet";
      link.href = "https://fonts.googleapis.com/css2?family=Atkinson+Hyperlegible:wght@400;700&display=swap";
      document.head.appendChild(link);
    }
    if (!document.getElementById("shard-dyslexia-style")) {
      const style = document.createElement("style");
      style.id = "shard-dyslexia-style";
      style.textContent = `
        body.shard-dyslexia, body.shard-dyslexia * {
          font-family: 'Atkinson Hyperlegible', 'Verdana', system-ui, sans-serif !important;
          letter-spacing: 0.025em !important;
          word-spacing: 0.06em !important;
          font-style: normal !important;
        }
        body.shard-dyslexia code, body.shard-dyslexia pre {
          font-family: 'Atkinson Hyperlegible', 'Verdana', monospace !important;
        }
        /* Wider paragraph spacing — clearer block boundaries */
        body.shard-dyslexia p {
          margin-top: 0 !important;
          margin-bottom: 1.4em !important;
        }
        body.shard-dyslexia li {
          margin-bottom: 0.4em !important;
        }
        /* Hide decorative backdrops to cut visual noise */
        body.shard-dyslexia canvas,
        body.shard-dyslexia [aria-hidden="true"] {
          display: none !important;
        }
      `;
      document.head.appendChild(style);
    }
    if (!document.getElementById("shard-line-spacing-style")) {
      const style = document.createElement("style");
      style.id = "shard-line-spacing-style";
      style.textContent = `
        body.shard-spacing-tight p,
        body.shard-spacing-tight li,
        body.shard-spacing-tight dd {
          line-height: 1.42 !important;
        }
        body.shard-spacing-roomy p,
        body.shard-spacing-roomy li,
        body.shard-spacing-roomy dd {
          line-height: 1.9 !important;
        }
      `;
      document.head.appendChild(style);
    }
  }, []);

  // Toggle dyslexia body class
  React.useEffect(() => {
    document.body.classList.toggle("shard-dyslexia", !!prefs.dyslexia);
  }, [prefs.dyslexia]);

  // Apply text-size as html zoom (the only thing that scales inline px font-sizes)
  React.useEffect(() => {
    const scale = window.TEXT_SCALES[prefs.textSize] || window.TEXT_SCALES.M;
    document.documentElement.style.zoom = scale.zoom;
  }, [prefs.textSize]);

  // Apply line-spacing class. Dyslexia forces Roomy.
  React.useEffect(() => {
    const cls = ["shard-spacing-tight", "shard-spacing-standard", "shard-spacing-roomy"];
    document.body.classList.remove(...cls);
    const effective = prefs.dyslexia ? "Roomy" : prefs.lineSpacing || "Standard";
    document.body.classList.add("shard-spacing-" + effective.toLowerCase());
  }, [prefs.lineSpacing, prefs.dyslexia]);

  if (!open) return null;

  const row = {
    display: "flex",
    flexDirection: "column",
    gap: 8,
    paddingBottom: 18,
    borderBottom: `1px solid ${theme.cardBorder}`,
    marginBottom: 18,
  };
  const seg = (active) => ({
    flex: 1,
    padding: "10px 8px",
    background: active ? theme.accent : "transparent",
    color: active ? theme.onAccent : theme.ink,
    border: `1px solid ${active ? theme.accent : theme.chipBorder}`,
    borderRadius: 8,
    fontSize: 13,
    fontWeight: 500,
    cursor: "pointer",
    fontFamily: "'DM Sans', sans-serif",
    transition: "all 150ms",
  });

  return (
    <div
      style={{
        position: "fixed",
        top: isMobile ? 64 : 80,
        right: isMobile ? 12 : 40,
        left: isMobile ? 12 : "auto",
        width: isMobile ? "auto" : 340,
        maxHeight: isMobile ? "calc(100vh - 80px)" : "auto",
        overflowY: isMobile ? "auto" : "visible",
        zIndex: 49,
        background: theme.surface,
        border: `1px solid ${theme.cardBorder}`,
        borderRadius: 16,
        padding: isMobile ? "20px 20px 16px" : "24px 24px 20px",
        color: theme.ink,
        fontFamily: "'DM Sans', sans-serif",
        boxShadow: theme.dark
          ? "0 30px 60px -20px rgba(0,0,0,0.6), 0 0 0 1px rgba(255,255,255,0.04)"
          : "0 30px 60px -20px rgba(0,0,0,0.2)",
      }}
    >
      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          marginBottom: 4,
        }}
      >
        <strong style={{ fontSize: 15, fontFamily: "'Lexend', sans-serif", fontWeight: 600 }}>
          Viewing Preferences
        </strong>
        <button
          onClick={onClose}
          aria-label="Close"
          style={{
            background: "transparent",
            border: "none",
            color: theme.sub,
            cursor: "pointer",
            fontSize: 18,
            lineHeight: 1,
          }}
        >
          ×
        </button>
      </div>
      <p style={{ fontSize: 12.5, color: theme.sub, margin: "0 0 22px 0", lineHeight: 1.5 }}>
        These settings stay with you while you browse. We don't track them.
      </p>

      <div style={row}>
        <label style={{ fontSize: 12.5, color: theme.sub, letterSpacing: 0.2 }}>Theme</label>
        <div style={{ display: "flex", gap: 8 }}>
          <button
            style={seg(prefs.theme === "midnight")}
            onClick={() => setPrefs({ ...prefs, theme: "midnight" })}
          >
            Midnight
          </button>
          <button
            style={seg(prefs.theme === "light")}
            onClick={() => setPrefs({ ...prefs, theme: "light" })}
          >
            Bone
          </button>
        </div>
      </div>

      <div style={row}>
        <label style={{ fontSize: 12.5, color: theme.sub, letterSpacing: 0.2 }}>Text size</label>
        <div style={{ display: "flex", gap: 8 }}>
          {["S", "M", "L"].map((s) => (
            <button
              key={s}
              style={seg(prefs.textSize === s)}
              onClick={() => setPrefs({ ...prefs, textSize: s })}
            >
              {s}
            </button>
          ))}
        </div>
      </div>

      <div style={row}>
        <label style={{ fontSize: 12.5, color: theme.sub, letterSpacing: 0.2 }}>Line spacing</label>
        <div style={{ display: "flex", gap: 8 }}>
          {["Tight", "Standard", "Roomy"].map((s) => (
            <button
              key={s}
              style={seg(prefs.lineSpacing === s)}
              onClick={() => setPrefs({ ...prefs, lineSpacing: s })}
            >
              {s}
            </button>
          ))}
        </div>
      </div>

      <div style={{ ...row, borderBottom: "none", marginBottom: 4, paddingBottom: 0 }}>
        <label
          style={{
            fontSize: 12.5,
            color: theme.sub,
            letterSpacing: 0.2,
            display: "flex",
            alignItems: "center",
            gap: 8,
          }}
        >
          Dyslexia-friendly mode
        </label>
        <div style={{ display: "flex", gap: 8 }}>
          <button
            style={seg(!!prefs.dyslexia)}
            onClick={() => setPrefs({ ...prefs, dyslexia: true })}
          >
            On
          </button>
          <button
            style={seg(!prefs.dyslexia)}
            onClick={() => setPrefs({ ...prefs, dyslexia: false })}
          >
            Off
          </button>
        </div>
        <p style={{ fontSize: 11.5, color: theme.mute, margin: "8px 0 0", lineHeight: 1.5 }}>
          Switches to Atkinson Hyperlegible, forces the Bone theme, drops italics, widens paragraph
          spacing, hides decorative backdrops, and turns off all animation.
        </p>
      </div>
    </div>
  );
}

window.Nav = Nav;
window.ShardLogo = ShardLogo;
window.ViewingPreferencesPanel = ViewingPreferencesPanel;
