/* ACCESSIBILITY WIDGET — תקנות שוויון זכויות לאנשים עם מוגבלות, התשע"ג-2013.
   Floating wheelchair button at bottom-left opens a panel of 9 visual adjustments.
   All preferences persist via localStorage and re-apply on next visit. */

const A11Y_PREFS_KEY = 'yakir-a11y-prefs';
const A11Y_FONT_STEPS = [0.9, 1.0, 1.1, 1.25, 1.5];
const A11Y_FONT_LABELS = ['90%', '100%', '110%', '125%', '150%'];
const A11Y_DEFAULTS = {
  fontStep: 1,            // index into A11Y_FONT_STEPS (1 = 100%)
  highContrast: false,
  grayscale: false,
  invert: false,
  links: false,
  headings: false,
  noAnim: false,
  readable: false,
  bigCursor: false,
};

const A11Y_CSS = `
  html.a11y-highcontrast { filter: contrast(1.4) saturate(0.9); }
  html.a11y-grayscale     { filter: grayscale(1); }
  html.a11y-invert        { filter: invert(1) hue-rotate(180deg); }
  html.a11y-invert img, html.a11y-invert video, html.a11y-invert canvas { filter: invert(1) hue-rotate(180deg); }
  html.a11y-links a       { text-decoration: underline !important; outline: 2px solid #EEB332 !important; outline-offset: 2px; font-weight: 700 !important; }
  html.a11y-headings h1, html.a11y-headings h2, html.a11y-headings h3, html.a11y-headings h4 { outline: 2px solid #EEB332 !important; outline-offset: 4px; }
  html.a11y-no-anim *, html.a11y-no-anim *::before, html.a11y-no-anim *::after { transition: none !important; animation: none !important; }
  html.a11y-readable * { font-family: Arial, 'Open Sans', sans-serif !important; letter-spacing: 0.04em !important; line-height: 1.7 !important; }
  html.a11y-bigcursor, html.a11y-bigcursor * {
    cursor: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='44' height='44' viewBox='0 0 24 24' fill='%23ffffff' stroke='%23000000' stroke-width='2'><path d='M3 3l7 18 3-8 8-3z'/></svg>") 4 4, auto !important;
  }
  @keyframes a11y-btn-pulse {
    0%,100% { box-shadow: 0 8px 22px rgba(0,0,0,0.45), 0 0 0 0 rgba(30,91,182,0.55); }
    50%     { box-shadow: 0 8px 22px rgba(0,0,0,0.45), 0 0 0 14px rgba(30,91,182,0); }
  }
  @keyframes a11y-panel-in {
    from { opacity: 0; transform: translateY(16px) scale(0.96); }
    to   { opacity: 1; transform: translateY(0) scale(1); }
  }
  @keyframes a11y-modal-in {
    from { opacity: 0; transform: scale(0.96); }
    to   { opacity: 1; transform: scale(1); }
  }
`;

function a11yLoadPrefs() {
  try {
    const raw = localStorage.getItem(A11Y_PREFS_KEY);
    if (!raw) return A11Y_DEFAULTS;
    return { ...A11Y_DEFAULTS, ...JSON.parse(raw) };
  } catch (e) { return A11Y_DEFAULTS; }
}
function a11ySavePrefs(prefs) {
  try { localStorage.setItem(A11Y_PREFS_KEY, JSON.stringify(prefs)); } catch (e) {}
}
function a11yApply(prefs) {
  const html = document.documentElement;
  html.classList.toggle('a11y-highcontrast', prefs.highContrast);
  html.classList.toggle('a11y-grayscale',    prefs.grayscale);
  html.classList.toggle('a11y-invert',       prefs.invert);
  html.classList.toggle('a11y-links',        prefs.links);
  html.classList.toggle('a11y-headings',     prefs.headings);
  html.classList.toggle('a11y-no-anim',      prefs.noAnim);
  html.classList.toggle('a11y-readable',     prefs.readable);
  html.classList.toggle('a11y-bigcursor',    prefs.bigCursor);
  const scale = A11Y_FONT_STEPS[prefs.fontStep] || 1;
  html.style.fontSize = scale === 1 ? '' : `${16 * scale}px`;
}

function Accessibility() {
  // Recursion guard for iframe contexts
  if (typeof window !== 'undefined' && window !== window.top) return null;

  const isMobile = useIsMobile();
  const [open, setOpen] = React.useState(false);
  const [stmtOpen, setStmtOpen] = React.useState(false);
  const [interacted, setInteracted] = React.useState(false);
  const [prefs, setPrefs] = React.useState(() => a11yLoadPrefs());

  React.useEffect(() => {
    a11ySavePrefs(prefs);
    a11yApply(prefs);
  }, [prefs]);

  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'Escape') {
        if (stmtOpen) setStmtOpen(false);
        else if (open) setOpen(false);
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, stmtOpen]);

  const toggle = (key) => setPrefs(p => ({ ...p, [key]: !p[key] }));
  const stepFont = (delta) => setPrefs(p => ({ ...p, fontStep: clamp(p.fontStep + delta, 0, A11Y_FONT_STEPS.length - 1) }));
  const reset = () => setPrefs(A11Y_DEFAULTS);

  return (
    <>
      <style>{A11Y_CSS}</style>
      <FloatingA11yButton
        isMobile={isMobile}
        expanded={open}
        showPulse={!interacted}
        onClick={() => { setOpen(o => !o); setInteracted(true); }}
      />
      {open && (
        <A11yPanel
          isMobile={isMobile}
          prefs={prefs}
          toggle={toggle}
          stepFont={stepFont}
          reset={reset}
          onClose={() => setOpen(false)}
          onStatement={() => setStmtOpen(true)}
        />
      )}
      {stmtOpen && (
        <A11yStatementModal isMobile={isMobile} onClose={() => setStmtOpen(false)} />
      )}
    </>
  );
}

/* ─────────────────────────────────────────────────────────────────────
   FLOATING BUTTON
   ───────────────────────────────────────────────────────────────────── */

function FloatingA11yButton({ isMobile, expanded, showPulse, onClick }) {
  const size = isMobile ? 34 : 39;
  const inset = isMobile ? 12 : 18;
  return (
    <button
      type="button"
      onClick={onClick}
      aria-label="פתח תפריט נגישות"
      aria-expanded={expanded}
      style={{
        position:'fixed', bottom: inset, left: inset,
        width: size, height: size, borderRadius:'50%',
        background:'#1E5BB6',
        border:'2px solid #ffffff',
        cursor:'pointer',
        display:'flex', alignItems:'center', justifyContent:'center',
        zIndex: 1000,
        boxShadow:'0 8px 22px rgba(0,0,0,0.45)',
        animation: showPulse ? 'a11y-btn-pulse 2.2s ease-in-out infinite' : 'none',
        transition:'transform 200ms cubic-bezier(0.22,1,0.36,1)',
        padding: 0,
      }}
      onMouseEnter={(e) => { e.currentTarget.style.transform = 'scale(1.08)'; }}
      onMouseLeave={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
    >
      <svg viewBox="0 0 24 24" width={isMobile ? 20 : 22} height={isMobile ? 20 : 22} fill="none" stroke="#ffffff" strokeWidth="2.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" focusable="false">
        {/* head */}
        <circle cx="12" cy="4.5" r="2.4" fill="#ffffff" stroke="none" />
        {/* arms (horizontal) + body (vertical) + diverging legs */}
        <path d="M 3.5 10 H 20.5 M 12 9 V 13.5 M 12 13.5 L 8.5 21.5 M 12 13.5 L 15.5 21.5" />
      </svg>
    </button>
  );
}

/* ─────────────────────────────────────────────────────────────────────
   PANEL
   ───────────────────────────────────────────────────────────────────── */

function A11yPanel({ isMobile, prefs, toggle, stepFont, reset, onClose, onStatement }) {
  const features = [
    { key:'highContrast', label:'ניגודיות גבוהה' },
    { key:'grayscale',    label:'גווני אפור' },
    { key:'invert',       label:'צבעים הפוכים' },
    { key:'links',        label:'הדגשת קישורים' },
    { key:'headings',     label:'הדגשת כותרות' },
    { key:'noAnim',       label:'עצירת אנימציות' },
    { key:'readable',     label:'גופן קריא' },
    { key:'bigCursor',    label:'סמן עכבר גדול' },
  ];

  const panelInset = isMobile ? 12 : 18;
  const panelBottom = (isMobile ? 48 : 56) + panelInset + 12; // button height + inset + gap

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-labelledby="a11y-panel-title"
      dir="rtl"
      style={{
        position:'fixed',
        bottom: panelBottom, left: panelInset,
        width: isMobile ? 'calc(100vw - 24px)' : 320,
        maxHeight: '80vh',
        background:'#13110F',
        border:'1px solid rgba(238,179,50,0.3)',
        borderRadius: 10,
        boxShadow:'0 20px 50px -10px rgba(0,0,0,0.7), 0 0 30px rgba(238,179,50,0.15)',
        zIndex: 1001,
        color:'#F5F2ED',
        fontFamily:'Open Sans, sans-serif',
        display:'flex', flexDirection:'column',
        animation:'a11y-panel-in 240ms cubic-bezier(0.22,1,0.36,1)',
        overflow:'hidden',
      }}
    >
      {/* Header */}
      <div style={{
        display:'flex', alignItems:'center', justifyContent:'space-between',
        padding:'14px 18px',
        borderBottom:'1px solid rgba(238,179,50,0.18)',
      }}>
        <h3 id="a11y-panel-title" style={{margin:0, fontFamily:'Open Sans, sans-serif', fontWeight:800, fontSize:18, color:'#F5F2ED'}}>נגישות</h3>
        <button
          type="button"
          onClick={onClose}
          aria-label="סגור תפריט נגישות"
          style={{
            background:'transparent', border:'1px solid rgba(245,242,237,0.2)', color:'#F5F2ED',
            width:30, height:30, borderRadius:'50%', cursor:'pointer',
            display:'flex', alignItems:'center', justifyContent:'center',
            fontSize:16, lineHeight:1, padding:0,
          }}
        >✕</button>
      </div>

      {/* Scrollable body */}
      <div style={{padding:14, overflowY:'auto', flex:1}}>

        {/* Font scale */}
        <div style={{marginBottom:14}}>
          <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:8, fontSize:14}}>
            <span style={{fontWeight:600}}>גודל טקסט</span>
            <span style={{color:'#EEB332', fontWeight:700, fontFamily:'monospace'}}>{A11Y_FONT_LABELS[prefs.fontStep]}</span>
          </div>
          <div style={{display:'flex', gap:8}}>
            <button
              type="button"
              onClick={() => stepFont(-1)}
              aria-label="הקטן טקסט"
              disabled={prefs.fontStep <= 0}
              style={a11yStepperStyle(prefs.fontStep <= 0)}
            >−</button>
            <button
              type="button"
              onClick={() => stepFont(1)}
              aria-label="הגדל טקסט"
              disabled={prefs.fontStep >= A11Y_FONT_STEPS.length - 1}
              style={a11yStepperStyle(prefs.fontStep >= A11Y_FONT_STEPS.length - 1)}
            >+</button>
          </div>
        </div>

        {/* Feature toggles */}
        <div style={{display:'flex', flexDirection:'column', gap:6}}>
          {features.map(f => (
            <A11yToggleRow
              key={f.key}
              label={f.label}
              checked={prefs[f.key]}
              onChange={() => toggle(f.key)}
            />
          ))}
        </div>

        {/* Reset */}
        <button
          type="button"
          onClick={reset}
          style={{
            marginTop:14, width:'100%',
            padding:'10px 14px',
            background:'transparent', color:'#F5F2ED',
            border:'1px solid rgba(245,242,237,0.25)',
            borderRadius:6,
            fontFamily:'Open Sans, sans-serif', fontWeight:600, fontSize:14,
            cursor:'pointer',
          }}
        >איפוס הגדרות</button>
      </div>

      {/* Footer — statement link */}
      <button
        type="button"
        onClick={onStatement}
        style={{
          padding:'12px 18px',
          background:'rgba(238,179,50,0.06)',
          border:'none', borderTop:'1px solid rgba(238,179,50,0.18)',
          color:'#EEB332',
          fontFamily:'Open Sans, sans-serif', fontWeight:600, fontSize:13,
          cursor:'pointer',
          letterSpacing:'0.04em',
        }}
      >הצהרת נגישות ←</button>
    </div>
  );
}

function a11yStepperStyle(disabled) {
  return {
    flex:1, height:44,
    background: disabled ? 'rgba(245,242,237,0.04)' : 'rgba(238,179,50,0.10)',
    color: disabled ? 'rgba(245,242,237,0.3)' : '#EEB332',
    border:`1px solid ${disabled ? 'rgba(245,242,237,0.1)' : 'rgba(238,179,50,0.4)'}`,
    borderRadius:6,
    fontSize:22, fontWeight:700, fontFamily:'Open Sans, sans-serif',
    cursor: disabled ? 'not-allowed' : 'pointer',
    display:'flex', alignItems:'center', justifyContent:'center',
    transition:'background 200ms',
  };
}

function A11yToggleRow({ label, checked, onChange }) {
  return (
    <button
      type="button"
      role="switch"
      aria-checked={checked}
      onClick={onChange}
      style={{
        display:'flex', alignItems:'center', justifyContent:'space-between',
        width:'100%', minHeight:44,
        padding:'8px 12px',
        background: checked ? 'rgba(238,179,50,0.12)' : 'rgba(245,242,237,0.03)',
        border:`1px solid ${checked ? '#EEB332' : 'rgba(245,242,237,0.08)'}`,
        borderRadius:6,
        cursor:'pointer',
        color: checked ? '#EEB332' : '#F5F2ED',
        fontFamily:'Open Sans, sans-serif', fontWeight: checked ? 600 : 500, fontSize:14,
        transition:'all 200ms',
      }}
    >
      <span>{label}</span>
      <span aria-hidden="true" style={{
        width:36, height:20, borderRadius:500,
        background: checked ? '#EEB332' : 'rgba(245,242,237,0.15)',
        position:'relative',
        transition:'background 200ms',
        flexShrink:0,
      }}>
        <span style={{
          position:'absolute', top:2, left: checked ? 18 : 2,
          width:16, height:16, borderRadius:'50%',
          background:'#0A0907',
          transition:'left 200ms cubic-bezier(0.22,1,0.36,1)',
        }} />
      </span>
    </button>
  );
}

/* ─────────────────────────────────────────────────────────────────────
   ACCESSIBILITY STATEMENT MODAL
   ───────────────────────────────────────────────────────────────────── */

function A11yStatementModal({ isMobile, onClose }) {
  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-labelledby="a11y-stmt-title"
      style={{
        position:'fixed', inset:0,
        background:'rgba(10,9,7,0.85)',
        backdropFilter:'blur(6px)', WebkitBackdropFilter:'blur(6px)',
        zIndex: 1002,
        display:'flex', alignItems:'center', justifyContent:'center',
        padding: isMobile ? 12 : 24,
      }}
      onClick={onClose}
    >
      <div
        dir="rtl"
        onClick={(e) => e.stopPropagation()}
        style={{
          width:'100%', maxWidth: 640,
          maxHeight:'90vh',
          background:'#13110F',
          border:'1px solid rgba(238,179,50,0.4)',
          borderRadius:10,
          boxShadow:'0 30px 70px -10px rgba(0,0,0,0.8), 0 0 40px rgba(238,179,50,0.18)',
          color:'#F5F2ED',
          fontFamily:'Open Sans, sans-serif',
          display:'flex', flexDirection:'column',
          animation:'a11y-modal-in 240ms cubic-bezier(0.22,1,0.36,1)',
          overflow:'hidden',
        }}
      >
        {/* Header */}
        <div style={{
          display:'flex', alignItems:'center', justifyContent:'space-between',
          padding: isMobile ? '14px 16px' : '18px 24px',
          borderBottom:'1px solid rgba(238,179,50,0.18)',
        }}>
          <h2 id="a11y-stmt-title" style={{margin:0, fontFamily:'Open Sans, sans-serif', fontWeight:800, fontSize: isMobile ? 18 : 22, color:'#F5F2ED'}}>הצהרת נגישות</h2>
          <button
            type="button"
            onClick={onClose}
            aria-label="סגור"
            style={{
              background:'transparent', border:'1px solid rgba(245,242,237,0.2)', color:'#F5F2ED',
              width:32, height:32, borderRadius:'50%', cursor:'pointer',
              display:'flex', alignItems:'center', justifyContent:'center',
              fontSize:16, lineHeight:1, padding:0,
            }}
          >✕</button>
        </div>

        {/* Body */}
        <div style={{
          padding: isMobile ? '16px 18px 22px' : '22px 28px 28px',
          overflowY:'auto',
          fontSize: isMobile ? 14 : 15,
          lineHeight: 1.7,
          color:'rgba(245,242,237,0.88)',
        }}>
          <p style={{margin:'0 0 14px'}}>
            אנו רואים בנגישות האתר ערך עליון ופועלים להתאים את האתר לרמת AA של תקן <b>WCAG 2.1</b> בהתאם
            ל<b>תקנות שוויון זכויות לאנשים עם מוגבלות (התאמות נגישות לשירות), התשע"ג-2013</b>.
          </p>

          <h3 style={{margin:'18px 0 8px', fontSize: isMobile ? 15 : 17, color:'#EEB332', fontWeight:700}}>מה הותאם באתר</h3>
          <ul style={{margin:0, paddingInlineStart:18, color:'rgba(245,242,237,0.85)'}}>
            <li style={{marginBottom:4}}>ניווט מלא באמצעות מקלדת (Tab + Enter + Esc)</li>
            <li style={{marginBottom:4}}>מבנה כותרות תקין ותגיות סמנטיות לטובת קוראי מסך</li>
            <li style={{marginBottom:4}}>תפריט נגישות צף המאפשר התאמת גודל טקסט, ניגודיות, גופן קריא, עצירת אנימציות ועוד</li>
            <li style={{marginBottom:4}}>ניגודיות צבעים מספקת בין טקסט לרקע</li>
            <li style={{marginBottom:4}}>תיאורים חלופיים לאלמנטים גרפיים מרכזיים</li>
          </ul>

          <h3 style={{margin:'18px 0 8px', fontSize: isMobile ? 15 : 17, color:'#EEB332', fontWeight:700}}>חריגים ידועים</h3>
          <ul style={{margin:0, paddingInlineStart:18, color:'rgba(245,242,237,0.85)'}}>
            <li style={{marginBottom:4}}>חלק מהסרטונים והאנימציות מבוססים על גלילה - ניתן לעצור אותם דרך תפריט הנגישות (״עצירת אנימציות״).</li>
            <li style={{marginBottom:4}}>האתר מותאם לדפדפנים מודרניים: Chrome, Edge, Safari, Firefox - בגרסאות עדכניות.</li>
          </ul>

          <h3 style={{margin:'18px 0 8px', fontSize: isMobile ? 15 : 17, color:'#EEB332', fontWeight:700}}>רכז נגישות</h3>
          <div style={{
            background:'rgba(238,179,50,0.06)',
            border:'1px solid rgba(238,179,50,0.2)',
            borderRadius:6,
            padding:'12px 14px',
            fontSize: isMobile ? 13 : 14,
            lineHeight:1.8,
          }}>
            <div><b>שם:</b> יקיר עבאדי</div>
            <div><b>טלפון:</b> [נא להזין]</div>
            <div><b>אימייל:</b> [נא להזין]</div>
          </div>

          <p style={{margin:'18px 0 0', fontSize: isMobile ? 13 : 14, color:'rgba(245,242,237,0.7)'}}>
            אם נתקלתם בבעיית נגישות באתר, אנא פנו אלינו ונפעל לתקנה תוך 14 ימי עסקים.
          </p>

          <p style={{margin:'14px 0 0', fontSize: isMobile ? 12 : 13, color:'#7A7773'}}>
            עדכון אחרון: [נא להזין תאריך]
          </p>
        </div>
      </div>
    </div>
  );
}

window.Accessibility = Accessibility;
