// Laad — Accessibility widget (floating button + panel)
// Provides: font size adjustment, high contrast, highlight links,
// readable font, reduced motion, and reset.

(function () {
  const { useState, useEffect, useRef } = React;

  const STORAGE_KEY = "laad_a11y_v1";
  const STYLE_TAG_ID = "laad-a11y-styles";

  const defaultPrefs = {
    fontScale: 1,        // 1 = base, multiplied by step
    contrast: false,     // high contrast
    highlightLinks: false,
    readableFont: false,
    reducedMotion: false,
    grayscale: false,
  };

  function loadPrefs() {
    try {
      const raw = localStorage.getItem(STORAGE_KEY);
      if (!raw) return { ...defaultPrefs };
      return { ...defaultPrefs, ...JSON.parse(raw) };
    } catch (e) {
      return { ...defaultPrefs };
    }
  }

  function savePrefs(prefs) {
    try { localStorage.setItem(STORAGE_KEY, JSON.stringify(prefs)); } catch (e) {}
  }

  function applyPrefs(prefs) {
    const html = document.documentElement;
    const body = document.body;

    // The site uses absolute pixel font sizes everywhere, so adjusting
    // html { font-size } has no effect. Use CSS `zoom` on body to scale
    // the entire page (text + layout) proportionally. Widely supported
    // including Firefox 126+.
    html.style.setProperty("--a11y-font-scale", prefs.fontScale);
    if (body) {
      body.style.zoom = prefs.fontScale !== 1 ? prefs.fontScale : "";
    }

    html.classList.toggle("a11y-contrast", prefs.contrast);
    html.classList.toggle("a11y-highlight-links", prefs.highlightLinks);
    html.classList.toggle("a11y-readable-font", prefs.readableFont);
    html.classList.toggle("a11y-reduced-motion", prefs.reducedMotion);
    html.classList.toggle("a11y-grayscale", prefs.grayscale);

    ensureStyleTag();
  }

  function ensureStyleTag() {
    if (document.getElementById(STYLE_TAG_ID)) return;
    const style = document.createElement("style");
    style.id = STYLE_TAG_ID;
    style.textContent = `
      html.a11y-contrast, html.a11y-contrast body { background: #000 !important; color: #fff !important; }
      html.a11y-contrast * {
        background-color: transparent !important;
        color: #fff !important;
        border-color: #fff !important;
        text-shadow: none !important;
        box-shadow: none !important;
      }
      html.a11y-contrast a, html.a11y-contrast button { color: #ffe600 !important; }
      html.a11y-contrast img, html.a11y-contrast video { filter: grayscale(1) contrast(1.2); }

      html.a11y-highlight-links a {
        outline: 2px solid #ffd000 !important;
        outline-offset: 2px;
        text-decoration: underline !important;
        background: rgba(255, 208, 0, 0.18) !important;
      }

      html.a11y-readable-font, html.a11y-readable-font body,
      html.a11y-readable-font * {
        font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif !important;
        letter-spacing: 0.02em !important;
        line-height: 1.6 !important;
      }

      html.a11y-reduced-motion *, html.a11y-reduced-motion *::before, html.a11y-reduced-motion *::after {
        animation-duration: 0s !important;
        animation-delay: 0s !important;
        transition-duration: 0s !important;
        transition-delay: 0s !important;
        scroll-behavior: auto !important;
      }

      html.a11y-grayscale { filter: grayscale(1); }

      .laad-a11y-fab:focus-visible,
      .laad-a11y-panel button:focus-visible {
        outline: 3px solid #ffd000;
        outline-offset: 2px;
      }
    `;
    document.head.appendChild(style);
  }

  const ICON_PERSON = (
    <svg width="26" height="26" viewBox="0 0 24 24" fill="none" aria-hidden="true">
      <circle cx="12" cy="12" r="11" stroke="currentColor" strokeWidth="1.5" />
      <circle cx="12" cy="6.5" r="1.6" fill="currentColor" />
      <path d="M5.5 9.5h13" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
      <path d="M12 9.8v4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
      <path d="M12 13.8l-2.6 5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
      <path d="M12 13.8l2.6 5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
    </svg>
  );

  function AccessibilityButton({ lang = "he" }) {
    const [open, setOpen] = useState(false);
    const [prefs, setPrefs] = useState(loadPrefs);
    const panelRef = useRef(null);
    const buttonRef = useRef(null);

    const isHe = lang === "he";
    const t = isHe
      ? {
          title: "תפריט נגישות",
          openAria: "פתיחת תפריט נגישות",
          closeAria: "סגירת תפריט נגישות",
          increase: "הגדל גופן",
          decrease: "הקטן גופן",
          fontReset: "איפוס גופן",
          contrast: "ניגודיות גבוהה",
          highlightLinks: "הדגשת קישורים",
          readableFont: "גופן קריא",
          reducedMotion: "צמצום אנימציות",
          grayscale: "גווני אפור",
          resetAll: "איפוס הכל",
          statement: "הצהרת נגישות",
        }
      : {
          title: "Accessibility menu",
          openAria: "Open accessibility menu",
          closeAria: "Close accessibility menu",
          increase: "Increase text",
          decrease: "Decrease text",
          fontReset: "Reset text",
          contrast: "High contrast",
          highlightLinks: "Highlight links",
          readableFont: "Readable font",
          reducedMotion: "Reduce motion",
          grayscale: "Grayscale",
          resetAll: "Reset all",
          statement: "Accessibility statement",
        };

    useEffect(() => { applyPrefs(prefs); savePrefs(prefs); }, [prefs]);

    useEffect(() => {
      if (!open) return;
      const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
      const onClick = (e) => {
        if (
          panelRef.current && !panelRef.current.contains(e.target) &&
          buttonRef.current && !buttonRef.current.contains(e.target)
        ) setOpen(false);
      };
      document.addEventListener("keydown", onKey);
      document.addEventListener("mousedown", onClick);
      return () => {
        document.removeEventListener("keydown", onKey);
        document.removeEventListener("mousedown", onClick);
      };
    }, [open]);

    const setFontScale = (scale) => setPrefs((p) => ({ ...p, fontScale: Math.min(1.6, Math.max(0.8, +scale.toFixed(2))) }));
    const toggle = (key) => setPrefs((p) => ({ ...p, [key]: !p[key] }));
    const resetAll = () => setPrefs({ ...defaultPrefs });

    // Position: opposite side of language toggle (which sits at bottom-left in he,
    // bottom-right in en). Accessibility lives at the matching, conventional corner:
    // bottom-right in he, bottom-left in en.
    const sideKey = isHe ? "right" : "left";

    const fabStyle = {
      position: "fixed",
      bottom: 24,
      [sideKey]: 24,
      zIndex: 101,
      width: 48,
      height: 48,
      borderRadius: "50%",
      border: "none",
      background: "#1f5d3a",
      color: "#fff",
      display: "flex",
      alignItems: "center",
      justifyContent: "center",
      cursor: "pointer",
      boxShadow: "0 4px 14px rgba(0,0,0,0.22)",
      padding: 0,
    };

    const panelStyle = {
      position: "fixed",
      bottom: 84,
      [sideKey]: 24,
      zIndex: 101,
      width: 280,
      maxWidth: "calc(100vw - 48px)",
      background: "#ffffff",
      color: "#1a1814",
      borderRadius: 14,
      boxShadow: "0 12px 32px rgba(0,0,0,0.22)",
      padding: 16,
      fontFamily: isHe ? "'Heebo', sans-serif" : "'Inter', sans-serif",
      direction: isHe ? "rtl" : "ltr",
      textAlign: isHe ? "right" : "left",
    };

    const headerStyle = {
      fontSize: 15,
      fontWeight: 600,
      margin: "0 0 12px",
      letterSpacing: "0.02em",
    };

    const rowStyle = { display: "flex", gap: 8, marginBottom: 8 };

    const btnBase = {
      flex: 1,
      padding: "9px 10px",
      border: "1px solid rgba(26,24,20,0.18)",
      borderRadius: 8,
      background: "#fff",
      color: "#1a1814",
      cursor: "pointer",
      fontSize: 13,
      fontFamily: "inherit",
      textAlign: "center",
    };

    const btnActive = {
      ...btnBase,
      background: "#1f5d3a",
      color: "#fff",
      borderColor: "#1f5d3a",
    };

    const fullBtn = (active, onClick, label) => (
      <button
        type="button"
        onClick={onClick}
        style={{ ...(active ? btnActive : btnBase), flex: "1 1 100%", marginBottom: 8 }}
        aria-pressed={!!active}
      >
        {label}
      </button>
    );

    return (
      <>
        <button
          ref={buttonRef}
          type="button"
          className="laad-a11y-fab"
          onClick={() => setOpen((o) => !o)}
          aria-label={open ? t.closeAria : t.openAria}
          aria-expanded={open}
          aria-controls="laad-a11y-panel"
          style={fabStyle}
          title={t.title}
        >
          {ICON_PERSON}
        </button>

        {open && (
          <div
            ref={panelRef}
            id="laad-a11y-panel"
            role="dialog"
            aria-label={t.title}
            className="laad-a11y-panel"
            style={panelStyle}
          >
            <div style={headerStyle}>{t.title}</div>

            <div style={rowStyle}>
              <button type="button" onClick={() => setFontScale(prefs.fontScale - 0.1)} style={btnBase} aria-label={t.decrease}>A−</button>
              <button type="button" onClick={() => setFontScale(1)} style={btnBase} aria-label={t.fontReset}>A</button>
              <button type="button" onClick={() => setFontScale(prefs.fontScale + 0.1)} style={btnBase} aria-label={t.increase}>A+</button>
            </div>

            {fullBtn(prefs.contrast,        () => toggle("contrast"),        t.contrast)}
            {fullBtn(prefs.highlightLinks,  () => toggle("highlightLinks"),  t.highlightLinks)}
            {fullBtn(prefs.readableFont,    () => toggle("readableFont"),    t.readableFont)}
            {fullBtn(prefs.reducedMotion,   () => toggle("reducedMotion"),   t.reducedMotion)}
            {fullBtn(prefs.grayscale,       () => toggle("grayscale"),       t.grayscale)}

            <button
              type="button"
              onClick={resetAll}
              style={{ ...btnBase, width: "100%", marginTop: 4, background: "#f3efe6" }}
            >
              {t.resetAll}
            </button>
          </div>
        )}
      </>
    );
  }

  // Apply persisted prefs as early as possible (before first paint of widget).
  applyPrefs(loadPrefs());

  window.LaadAccessibilityButton = AccessibilityButton;
})();
