/* global React */

// ─────────────────────────────────────────────────────────────
// Accessibility panel — font sizing, contrast, motion, Easy English,
// read-aloud, and language. Settings persist in localStorage.
// ─────────────────────────────────────────────────────────────

const A11Y_KEY = 'cs-a11y-v1';

const A11Y_DEFAULTS = {
  fontSize: 'M',        // M | L | XL
  highContrast: false,
  reduceMotion: false,
  underlineLinks: false,
  easyEnglish: false,
};

const useA11y = () => {
  const [settings, setSettings] = React.useState(() => {
    try {
      const s = JSON.parse(localStorage.getItem(A11Y_KEY) || '{}');
      return { ...A11Y_DEFAULTS, ...s };
    } catch { return A11Y_DEFAULTS; }
  });
  React.useEffect(() => {
    try { localStorage.setItem(A11Y_KEY, JSON.stringify(settings)); } catch {}
    const html = document.documentElement;
    html.classList.toggle('a11y-large',   settings.fontSize === 'L');
    html.classList.toggle('a11y-xlarge',  settings.fontSize === 'XL');
    html.classList.toggle('a11y-high-contrast', settings.highContrast);
    html.classList.toggle('a11y-no-motion',     settings.reduceMotion);
    html.classList.toggle('a11y-underline',     settings.underlineLinks);
    html.classList.toggle('a11y-easy-english',  settings.easyEnglish);
  }, [settings]);
  const update = (k, v) => setSettings(s => ({ ...s, [k]: v }));
  const reset = () => setSettings(A11Y_DEFAULTS);
  return [settings, update, reset];
};

// Common languages relevant to Australian audiences
const A11Y_LANGUAGES = [
  { code: 'en',     label: 'English (default)' },
  { code: 'zh-CN',  label: '中文 · Chinese (Simplified)' },
  { code: 'zh-TW',  label: '繁體中文 · Chinese (Traditional)' },
  { code: 'vi',     label: 'Tiếng Việt · Vietnamese' },
  { code: 'ar',     label: 'العربية · Arabic' },
  { code: 'el',     label: 'Ελληνικά · Greek' },
  { code: 'it',     label: 'Italiano · Italian' },
  { code: 'es',     label: 'Español · Spanish' },
  { code: 'hi',     label: 'हिन्दी · Hindi' },
  { code: 'tl',     label: 'Tagalog · Filipino' },
  { code: 'ko',     label: '한국어 · Korean' },
  { code: 'ja',     label: '日本語 · Japanese' },
  { code: 'pa',     label: 'ਪੰਜਾਬੀ · Punjabi' },
  { code: 'fr',     label: 'Français · French' },
];

const AccessibilityPanel = () => {
  const [open, setOpen] = React.useState(false);
  const [settings, update, reset] = useA11y();
  const [reading, setReading] = React.useState(false);

  // Cancel speech on unmount
  React.useEffect(() => () => {
    if (window.speechSynthesis) window.speechSynthesis.cancel();
  }, []);

  const speak = () => {
    if (!window.speechSynthesis) return;
    if (reading) {
      window.speechSynthesis.cancel();
      setReading(false);
      return;
    }
    const main = document.querySelector('main');
    if (!main) return;
    // Collect visible text, skip script/style
    const text = main.innerText.replace(/\s+/g, ' ').trim();
    if (!text) return;
    const utterance = new SpeechSynthesisUtterance(text);
    utterance.rate = 0.95;
    utterance.pitch = 1;
    utterance.lang = 'en-AU';
    utterance.onend   = () => setReading(false);
    utterance.onerror = () => setReading(false);
    window.speechSynthesis.cancel();
    window.speechSynthesis.speak(utterance);
    setReading(true);
  };

  const translate = (code) => {
    if (!code || code === 'en') return;
    const url = `https://translate.google.com/translate?sl=en&tl=${code}&u=${encodeURIComponent(window.location.href)}`;
    window.open(url, '_blank', 'noopener');
  };

  // Styles — match CS aesthetic
  const fab = {
    position: 'fixed', left: 16, bottom: 16, zIndex: 60,
    height: 48, padding: '0 18px 0 14px',
    background: 'var(--ink)', color: 'var(--paper)',
    border: '1px solid var(--ink)', borderRadius: 999,
    fontFamily: 'var(--font-sans)', fontSize: 12, fontWeight: 700,
    letterSpacing: '0.08em', textTransform: 'uppercase',
    display: 'inline-flex', alignItems: 'center', gap: 10,
    cursor: 'pointer',
    boxShadow: '0 12px 28px -16px rgba(10,10,10,0.45)',
    transition: 'transform 200ms var(--ease-stage), background 200ms var(--ease-stage)',
  };

  const panel = {
    position: 'fixed', left: 16, bottom: 16, zIndex: 61,
    width: 360, maxWidth: 'calc(100vw - 32px)',
    maxHeight: 'calc(100vh - 32px)',
    background: 'var(--paper)', color: 'var(--ink)',
    border: '1px solid var(--ink)',
    fontFamily: 'var(--font-sans)',
    display: 'flex', flexDirection: 'column',
    boxShadow: '0 24px 60px -24px rgba(10,10,10,0.32)',
    animation: 'cs-fade-up 320ms var(--ease-stage) both',
  };

  const sectionStyle = {
    padding: '20px 22px', borderBottom: '1px solid var(--hairline)',
    display: 'flex', flexDirection: 'column', gap: 14,
  };

  const labelStyle = {
    fontSize: 11, fontWeight: 700, letterSpacing: '0.08em',
    textTransform: 'uppercase', color: 'var(--mid)',
  };

  const segBtn = (active) => ({
    flex: 1, height: 38, border: '1px solid ' + (active ? 'var(--ink)' : 'var(--hairline)'),
    background: active ? 'var(--ink)' : 'transparent',
    color: active ? 'var(--paper)' : 'var(--ink)',
    fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: 12,
    letterSpacing: '0.04em', textTransform: 'uppercase',
    cursor: 'pointer', borderRadius: 0,
    transition: 'background 160ms var(--ease-stage), color 160ms var(--ease-stage), border-color 160ms var(--ease-stage)',
  });

  const Row = ({ label, value, onToggle }) => (
    <label style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, cursor: 'pointer' }}>
      <span style={{ fontSize: 14, fontWeight: 700, letterSpacing: '-0.01em', color: 'var(--ink)' }}>{label}</span>
      <button
        type="button"
        onClick={onToggle}
        aria-pressed={value}
        style={{
          position: 'relative', width: 42, height: 22,
          background: value ? 'var(--ink)' : 'transparent',
          border: '1px solid var(--ink)', borderRadius: 999,
          cursor: 'pointer', padding: 0,
          transition: 'background 160ms var(--ease-stage)',
        }}
      >
        <span style={{
          position: 'absolute', top: 2, left: value ? 22 : 2,
          width: 16, height: 16, borderRadius: '50%',
          background: value ? 'var(--paper)' : 'var(--ink)',
          transition: 'left 200ms var(--ease-stage), background 160ms var(--ease-stage)',
        }} />
      </button>
    </label>
  );

  if (!open) {
    return (
      <button
        onClick={() => setOpen(true)}
        aria-label="Open accessibility tools"
        style={fab}
      >
        {/* Universal access symbol */}
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="square" aria-hidden>
          <circle cx="12" cy="4.5" r="1.8" fill="currentColor" />
          <path d="M5 9 L12 9 L19 9" />
          <path d="M9 9 L9 22" />
          <path d="M15 9 L15 22" />
          <path d="M9 15 L15 15" />
        </svg>
        Accessibility
      </button>
    );
  }

  return (
    <div style={panel} role="dialog" aria-label="Accessibility tools">
      {/* Header */}
      <div style={{ padding: '16px 18px 14px 22px', borderBottom: '1px solid var(--ink)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div>
          <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--mid)', marginBottom: 2 }}>
            Accessibility
          </div>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 22, letterSpacing: '-0.02em', lineHeight: 1 }}>
            View options
          </div>
        </div>
        <button
          type="button"
          onClick={() => setOpen(false)}
          aria-label="Close"
          style={{
            width: 32, height: 32, border: '1px solid var(--ink)',
            background: 'transparent', cursor: 'pointer', borderRadius: 0,
            fontFamily: 'var(--font-display)', fontSize: 16, lineHeight: 1,
          }}
        >×</button>
      </div>

      <div style={{ overflowY: 'auto' }}>
        {/* Font size */}
        <div style={sectionStyle}>
          <div style={labelStyle}>Text size</div>
          <div style={{ display: 'flex', gap: 8 }}>
            {[
              { id: 'M',  label: 'A',   size: 13 },
              { id: 'L',  label: 'A+',  size: 16 },
              { id: 'XL', label: 'A++', size: 19 },
            ].map(opt => (
              <button
                key={opt.id} type="button" onClick={() => update('fontSize', opt.id)}
                aria-pressed={settings.fontSize === opt.id}
                style={{ ...segBtn(settings.fontSize === opt.id), fontSize: opt.size, height: 44 }}
              >{opt.label}</button>
            ))}
          </div>
        </div>

        {/* Toggles */}
        <div style={sectionStyle}>
          <div style={labelStyle}>Reading & motion</div>
          <Row label="High contrast"
               value={settings.highContrast} onToggle={() => update('highContrast', !settings.highContrast)} />
          <Row label="Underline links"
               value={settings.underlineLinks} onToggle={() => update('underlineLinks', !settings.underlineLinks)} />
          <Row label="Reduce motion"
               value={settings.reduceMotion} onToggle={() => update('reduceMotion', !settings.reduceMotion)} />
          <Row label="Easy English"
               value={settings.easyEnglish} onToggle={() => update('easyEnglish', !settings.easyEnglish)} />
          <div style={{ fontSize: 12, lineHeight: 1.5, color: 'var(--mid)' }}>
            Easy English shows short sentences and plain words instead of the long versions.
          </div>
        </div>

        {/* Read aloud */}
        <div style={sectionStyle}>
          <div style={labelStyle}>Read this page</div>
          <button
            type="button" onClick={speak}
            disabled={typeof window !== 'undefined' && !window.speechSynthesis}
            style={{
              height: 44, border: '1px solid var(--ink)',
              background: reading ? 'var(--ink)' : 'transparent',
              color: reading ? 'var(--paper)' : 'var(--ink)',
              fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: 12,
              letterSpacing: '0.08em', textTransform: 'uppercase',
              cursor: 'pointer', borderRadius: 0, padding: '0 16px',
              display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8,
              transition: 'background 160ms var(--ease-stage), color 160ms var(--ease-stage)',
            }}
          >
            <span>{reading ? 'Stop reading' : 'Read aloud'}</span>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, opacity: 0.7 }}>
              {reading ? '■' : '▶'}
            </span>
          </button>
          {typeof window !== 'undefined' && !window.speechSynthesis && (
            <div style={{ fontSize: 11, color: 'var(--mid)' }}>Read aloud is not supported by your browser.</div>
          )}
        </div>

        {/* Language */}
        <div style={{ ...sectionStyle, borderBottom: 'none' }}>
          <div style={labelStyle}>Language</div>
          <select
            onChange={(e) => translate(e.target.value)}
            defaultValue="en"
            style={{
              height: 44, padding: '0 14px',
              background: 'transparent', border: '1px solid var(--ink)',
              fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: 700,
              color: 'var(--ink)', borderRadius: 0, outline: 'none', cursor: 'pointer',
              appearance: 'none', WebkitAppearance: 'none',
              backgroundImage: 'url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\' width=\'12\' height=\'8\' viewBox=\'0 0 12 8\'><path d=\'M1 1l5 5 5-5\' stroke=\'%230A0A0A\' stroke-width=\'1.5\' fill=\'none\' stroke-linecap=\'square\'/></svg>")',
              backgroundRepeat: 'no-repeat', backgroundPosition: 'right 14px center', paddingRight: 36,
            }}
          >
            {A11Y_LANGUAGES.map(l => (
              <option key={l.code} value={l.code}>{l.label}</option>
            ))}
          </select>
          <div style={{ fontSize: 12, lineHeight: 1.5, color: 'var(--mid)' }}>
            Opens this page in your chosen language via Google Translate.
          </div>
        </div>
      </div>

      {/* Footer — reset */}
      <div style={{ padding: '12px 22px', borderTop: '1px solid var(--ink)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--mid)', letterSpacing: '0.04em' }}>
          Saved on this device
        </span>
        <button type="button" onClick={reset}
          style={{
            background: 'transparent', border: 0, padding: 0, cursor: 'pointer',
            fontFamily: 'var(--font-sans)', fontSize: 11, fontWeight: 700,
            letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ink)',
          }}
        >Reset →</button>
      </div>
    </div>
  );
};

Object.assign(window, { AccessibilityPanel });
