// AccessibilityWidget — a lightweight, user-controlled preferences panel.
// NOT an "auto-fix" overlay: it just sets real CSS preferences (persisted in
// localStorage) that complement assistive tech rather than fighting it.
// The matching CSS lives in colors_and_type.css under "Accessibility preferences".

const A11Y_KEY = "kidlink-a11y";
const A11Y_DEFAULTS = { textScale: 0, contrast: false, links: false, readable: false, motion: false };

function readA11y() {
  try { return { ...A11Y_DEFAULTS, ...JSON.parse(localStorage.getItem(A11Y_KEY) || "{}") }; }
  catch (e) { return { ...A11Y_DEFAULTS }; }
}

function applyA11y(s) {
  const el = document.documentElement;
  el.classList.toggle("a11y-text-1", s.textScale === 1);
  el.classList.toggle("a11y-text-2", s.textScale === 2);
  el.classList.toggle("a11y-contrast", !!s.contrast);
  el.classList.toggle("a11y-links", !!s.links);
  el.classList.toggle("a11y-readable", !!s.readable);
  el.classList.toggle("a11y-motion", !!s.motion);
}

function AccessibilityWidget() {
  const [open, setOpen] = useState(false);
  const [settings, setSettings] = useState(readA11y);
  const panelRef = useRef(null);
  const btnRef = useRef(null);

  useEffect(() => {
    applyA11y(settings);
    try { localStorage.setItem(A11Y_KEY, JSON.stringify(settings)); } catch (e) {}
  }, [settings]);

  useEffect(() => {
    if (open && panelRef.current) {
      const first = panelRef.current.querySelector("button");
      if (first) first.focus();
    }
  }, [open]);

  const set = (patch) => setSettings((s) => ({ ...s, ...patch }));
  const reset = () => setSettings({ ...A11Y_DEFAULTS });
  const anyOn = settings.textScale > 0 || settings.contrast || settings.links || settings.readable || settings.motion;

  const onKeyDown = (e) => {
    if (e.key === "Escape") { setOpen(false); if (btnRef.current) btnRef.current.focus(); }
  };

  const rowStyle = (active) => ({
    display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12,
    width: "100%", textAlign: "left", padding: "12px 14px", cursor: "pointer",
    border: `1.5px solid ${active ? "var(--kl-plum)" : "var(--kl-border)"}`,
    background: active ? "var(--kl-plum-lightest)" : "var(--kl-white)",
    color: "var(--kl-fg-1)", borderRadius: "var(--kl-radius-button)",
    fontFamily: "var(--kl-font-body)", fontSize: "var(--kl-text-regular)", fontWeight: 600,
  });

  const Toggle = ({ label, icon, active, onToggle }) => (
    <button type="button" role="switch" aria-checked={active} onClick={onToggle} style={rowStyle(active)}>
      <span style={{ display: "flex", alignItems: "center", gap: 12 }}>
        <MIcon name={icon} size={22} color={active ? "var(--kl-plum)" : "var(--kl-fg-2)"} />
        {label}
      </span>
      <span aria-hidden="true" style={{
        flexShrink: 0, width: 40, height: 24, borderRadius: 999, padding: 3,
        background: active ? "var(--kl-plum)" : "var(--kl-gray-nurse-dark)",
        display: "inline-flex", justifyContent: active ? "flex-end" : "flex-start",
        transition: "background 0.15s ease",
      }}>
        <span style={{ width: 18, height: 18, borderRadius: 999, background: "var(--kl-white)" }} />
      </span>
    </button>
  );

  return (
    <div onKeyDown={onKeyDown}>
      {/* Launcher button */}
      <button
        ref={btnRef}
        type="button"
        aria-label="Accessibility options"
        aria-expanded={open}
        onClick={() => setOpen((o) => !o)}
        style={{
          position: "fixed", right: 20, bottom: 20, zIndex: 1000,
          width: 52, height: 52, borderRadius: 999, border: "2px solid var(--kl-white)",
          background: "var(--kl-plum)", color: "var(--kl-white)", cursor: "pointer",
          display: "inline-flex", alignItems: "center", justifyContent: "center",
          boxShadow: "0 6px 20px rgba(20,16,24,0.28)",
        }}
      >
        <MIcon name="accessibility_new" size={28} color="var(--kl-white)" />
      </button>

      {/* Preferences panel */}
      {open && (
        <div
          ref={panelRef}
          role="dialog"
          aria-label="Accessibility preferences"
          style={{
            position: "fixed", right: 20, bottom: 84, zIndex: 1000, boxSizing: "border-box",
            width: "min(360px, calc(100vw - 40px))", maxHeight: "calc(100vh - 120px)", overflowY: "auto",
            background: "var(--kl-white)", border: "1px solid var(--kl-border)",
            borderRadius: "var(--kl-radius-card-lg)", boxShadow: "0 16px 44px rgba(20,16,24,0.24)",
            padding: 20,
          }}
        >
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 8 }}>
            <h2 style={{ fontSize: "var(--kl-text-h5)", margin: 0 }}>Accessibility</h2>
            <button type="button" aria-label="Close accessibility options" onClick={() => setOpen(false)}
              style={{ border: "none", background: "transparent", cursor: "pointer", display: "inline-flex", padding: 4 }}>
              <MIcon name="close" size={22} color="var(--kl-fg-2)" />
            </button>
          </div>
          <p style={{ fontSize: "var(--kl-text-small)", color: "var(--kl-fg-2)", marginTop: 0, marginBottom: 18 }}>
            Adjust the display to suit you. Your choices are saved on this device.
          </p>

          {/* Text size */}
          <p style={{ fontSize: "var(--kl-text-small)", fontWeight: 700, marginBottom: 8 }}>Text size</p>
          <div role="group" aria-label="Text size" style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 8, marginBottom: 18 }}>
            {[{ l: "Default", v: 0, s: 15 }, { l: "Large", v: 1, s: 18 }, { l: "Larger", v: 2, s: 21 }].map((o) => {
              const active = settings.textScale === o.v;
              return (
                <button key={o.v} type="button" aria-pressed={active} onClick={() => set({ textScale: o.v })}
                  style={{
                    padding: "10px 6px", cursor: "pointer", borderRadius: "var(--kl-radius-button)",
                    border: `1.5px solid ${active ? "var(--kl-plum)" : "var(--kl-border)"}`,
                    background: active ? "var(--kl-plum-lightest)" : "var(--kl-white)",
                    color: "var(--kl-fg-1)", fontWeight: 700, fontFamily: "var(--kl-font-body)",
                  }}>
                  <span style={{ fontSize: o.s, lineHeight: 1 }}>A</span>
                  <span style={{ display: "block", fontSize: "0.72rem", fontWeight: 600, marginTop: 4, color: "var(--kl-fg-2)" }}>{o.l}</span>
                </button>
              );
            })}
          </div>

          {/* Toggles */}
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            <Toggle label="High contrast" icon="contrast" active={settings.contrast} onToggle={() => set({ contrast: !settings.contrast })} />
            <Toggle label="Highlight links" icon="link" active={settings.links} onToggle={() => set({ links: !settings.links })} />
            <Toggle label="Readable font" icon="text_fields" active={settings.readable} onToggle={() => set({ readable: !settings.readable })} />
            <Toggle label="Reduce motion" icon="motion_photos_off" active={settings.motion} onToggle={() => set({ motion: !settings.motion })} />
          </div>

          {anyOn && (
            <button type="button" onClick={reset}
              style={{
                marginTop: 16, width: "100%", padding: "10px 14px", cursor: "pointer",
                border: "1.5px solid var(--kl-border)", background: "var(--kl-white)", color: "var(--kl-fg-1)",
                borderRadius: "var(--kl-radius-button)", fontWeight: 700, fontFamily: "var(--kl-font-body)",
                display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8,
              }}>
              <MIcon name="restart_alt" size={18} color="var(--kl-fg-2)" />
              Reset all
            </button>
          )}
        </div>
      )}
    </div>
  );
}

window.AccessibilityWidget = AccessibilityWidget;
