// Shared components — topbar, footer, a11y panel, listen chip, tweaks panel
const { useState, useEffect, useRef } = React;

// ========== LISTEN CHIP (text-to-speech / audio first) ==========
function ListenChip({ text, label = "Lyt højt", compact = false }) {
  const [playing, setPlaying] = useState(false);
  const utterRef = useRef(null);

  const toggle = () => {
    if (!('speechSynthesis' in window)) return;
    if (playing) {
      window.speechSynthesis.cancel();
      setPlaying(false);
      return;
    }
    const u = new SpeechSynthesisUtterance(text);
    u.lang = 'da-DK';
    u.rate = 0.95;
    u.onend = () => setPlaying(false);
    u.onerror = () => setPlaying(false);
    utterRef.current = u;
    window.speechSynthesis.speak(u);
    setPlaying(true);
  };

  useEffect(() => () => window.speechSynthesis?.cancel(), []);

  return (
    <button className={"listen-chip" + (playing ? " playing" : "")} onClick={toggle} aria-label={playing ? "Stop oplæsning" : "Læs teksten højt"}>
      <span className="wave" aria-hidden="true">
        {playing ? (
          <svg viewBox="0 0 16 16"><rect x="3" y="3" width="3" height="10" rx="1"/><rect x="10" y="3" width="3" height="10" rx="1"/></svg>
        ) : (
          <svg viewBox="0 0 16 16"><path d="M4 5v6h2l4 3V2L6 5H4z"/><path d="M11.5 4.5a3 3 0 010 7" stroke="white" strokeWidth="1.2" fill="none" strokeLinecap="round"/></svg>
        )}
      </span>
      {!compact && (playing ? "Stop" : label)}
    </button>
  );
}

// ========== TOPBAR ==========
function Topbar({ current, spotsStyle = 'bar' }) {
  const links = [
    { id: 'forside', label: 'Forside', href: 'forside.html' },
    { id: 'hverdag', label: 'Hverdagen', href: 'hverdag.html' },
    { id: 'ordblind', label: 'For ordblinde', href: '#' },
    { id: 'besog', label: 'Besøg os', href: 'besog.html' },
    { id: 'kontakt', label: 'Kontakt', href: '#' },
  ];
  return (
    <>
      {spotsStyle === 'bar' && (
        <div className="spots-bar" role="status">
          <span className="pulse" aria-hidden="true"></span>
          <span>Vi har <strong>ledige pladser</strong> til skoleåret 26/27 — 8., 9. og 10. klasse</span>
          <a href="besog.html">Se hvordan du kommer ind →</a>
        </div>
      )}
      <header className="topbar">
        <div className="topbar-inner">
          <a href="forside.html" className="logo" aria-label="Emmerske Efterskole forside">
            <span className="logo-mark" aria-hidden="true">E</span>
            <span className="logo-text">
              <span className="name">Emmerske Efterskole</span>
              <span className="tag">Trivselsefterskolen</span>
            </span>
          </a>
          <nav className="nav" aria-label="Hovednavigation">
            {links.map(l => (
              <a key={l.id} href={l.href} className={current === l.id ? 'active' : ''}>{l.label}</a>
            ))}
          </nav>
          <div className="topbar-right">
            <ListenChip text="Velkommen til Emmerske Efterskole — trivselsefterskolen for ordblinde elever i 8., 9. og 10. klasse." compact />
            <a href="besog.html" className="btn btn-primary">Søg om plads</a>
          </div>
        </div>
      </header>
    </>
  );
}

// ========== A11Y PANEL ==========
function A11yPanel() {
  const [open, setOpen] = useState(false);
  const [font, setFont] = useState('default');
  const [size, setSize] = useState('default');
  const [contrast, setContrast] = useState('default');
  const [spacing, setSpacing] = useState(false);

  useEffect(() => {
    const b = document.body;
    if (font === 'dyslexic') b.setAttribute('data-dyslexic-font', 'true'); else b.removeAttribute('data-dyslexic-font');
    b.setAttribute('data-fontsize', size);
    b.setAttribute('data-contrast', contrast);
    if (spacing) b.setAttribute('data-spacing', 'wide'); else b.removeAttribute('data-spacing');
  }, [font, size, contrast, spacing]);

  return (
    <>
      <button className="a11y-fab" onClick={() => setOpen(!open)} aria-label="Tilgængelighedsindstillinger" aria-expanded={open}>
        <svg viewBox="0 0 32 32" fill="currentColor" aria-hidden="true">
          <circle cx="16" cy="6" r="3"/>
          <path d="M8 10 L24 10 L24 12 L18 12 L18 28 L16 28 L16 20 L14 20 L14 28 L12 28 L12 12 L8 12 Z"/>
        </svg>
      </button>
      {open && (
        <div className="a11y-panel" role="dialog" aria-label="Tilgængelighed">
          <h4>Gør siden nemmere</h4>
          <div className="subt">Vælg det der hjælper dig bedst.</div>

          <div className="a11y-row">
            <span className="a11y-label">Skriftstørrelse</span>
            <div className="a11y-btn-group">
              {[['default', 'A'], ['large', 'A+'], ['xlarge', 'A++']].map(([v, l]) => (
                <button key={v} className={"a11y-btn" + (size === v ? " active" : "")} onClick={() => setSize(v)}>{l}</button>
              ))}
            </div>
          </div>

          <div className="a11y-row">
            <span className="a11y-label">Farver</span>
            <div className="a11y-btn-group">
              <button className={"a11y-btn" + (contrast === 'default' ? " active" : "")} onClick={() => setContrast('default')}>Standard</button>
              <button className={"a11y-btn" + (contrast === 'warm' ? " active" : "")} onClick={() => setContrast('warm')}>Varm</button>
              <button className={"a11y-btn" + (contrast === 'high' ? " active" : "")} onClick={() => setContrast('high')}>Høj kontrast</button>
            </div>
          </div>

          <div className="a11y-switch">
            <div>
              <div style={{fontWeight: 700, fontSize: 14, color: 'var(--green-deep)'}}>Ordblinde-venlig font</div>
              <div style={{fontSize: 12, color: 'var(--ink-soft)'}}>Mere luft mellem bogstaver</div>
            </div>
            <button className={"switch" + (font === 'dyslexic' ? " on" : "")} onClick={() => setFont(font === 'dyslexic' ? 'default' : 'dyslexic')} aria-pressed={font === 'dyslexic'} aria-label="Toggle ordblinde-venlig font" />
          </div>

          <div className="a11y-switch">
            <div>
              <div style={{fontWeight: 700, fontSize: 14, color: 'var(--green-deep)'}}>Ekstra linjeafstand</div>
              <div style={{fontSize: 12, color: 'var(--ink-soft)'}}>Nemmere at følge linjerne</div>
            </div>
            <button className={"switch" + (spacing ? " on" : "")} onClick={() => setSpacing(!spacing)} aria-pressed={spacing} aria-label="Toggle ekstra linjeafstand" />
          </div>

          <div style={{marginTop: 16, padding: 12, background: 'var(--green-soft)', borderRadius: 10, fontSize: 12, color: 'var(--green-deep)'}}>
            💡 Du kan også få hele siden læst op med højttaler-knappen.
          </div>
        </div>
      )}
    </>
  );
}

// ========== FOOTER ==========
function Footer() {
  return (
    <footer className="footer">
      <div className="footer-inner">
        <div className="footer-grid">
          <div>
            <div className="brand-text">Emmerske<br/>Efterskole</div>
            <div className="brand-sub">Trivselsefterskolen — et trygt sted at være ung og ordblind. 8., 9. og 10. klasse.</div>
            <div style={{marginTop: 20, display: 'flex', gap: 10}}>
              <a href="#" aria-label="Instagram" style={{width: 40, height: 40, borderRadius: '50%', background: 'rgba(247,243,234,0.1)', display: 'grid', placeItems: 'center', padding: 0}}>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="3" width="18" height="18" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.5" cy="6.5" r="1" fill="currentColor"/></svg>
              </a>
              <a href="#" aria-label="Facebook" style={{width: 40, height: 40, borderRadius: '50%', background: 'rgba(247,243,234,0.1)', display: 'grid', placeItems: 'center', padding: 0}}>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M14 9h3V5h-3c-2.2 0-4 1.8-4 4v2H7v4h3v8h4v-8h3l1-4h-4V9c0-.6.4-1 1-1z"/></svg>
              </a>
              <a href="#" aria-label="YouTube" style={{width: 40, height: 40, borderRadius: '50%', background: 'rgba(247,243,234,0.1)', display: 'grid', placeItems: 'center', padding: 0}}>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M21.5 7.5a2.5 2.5 0 00-1.8-1.8C18 5.2 12 5.2 12 5.2s-6 0-7.7.5A2.5 2.5 0 002.5 7.5C2 9.2 2 12 2 12s0 2.8.5 4.5c.3.9 1 1.5 1.8 1.8 1.7.5 7.7.5 7.7.5s6 0 7.7-.5c.9-.3 1.5-1 1.8-1.8.5-1.7.5-4.5.5-4.5s0-2.8-.5-4.5zM10 15V9l5 3-5 3z"/></svg>
              </a>
            </div>
          </div>
          <div>
            <h4>Skolen</h4>
            <a href="#">Om Emmerske</a>
            <a href="#">Værdigrundlag</a>
            <a href="#">Medarbejdere</a>
            <a href="hverdag.html">Hverdagen</a>
            <a href="#">Fag og linjefag</a>
          </div>
          <div>
            <h4>Optagelse</h4>
            <a href="besog.html">Besøg os</a>
            <a href="besog.html">Søg om plads</a>
            <a href="#">Ledige pladser</a>
            <a href="#">Priser og tilskud</a>
            <a href="#">Åbent hus</a>
          </div>
          <div>
            <h4>Kontakt</h4>
            <a href="tel:+4574670466">74 67 04 66</a>
            <a href="mailto:kontor@emmerske.dk">kontor@emmerske.dk</a>
            <div style={{color: 'rgba(247,243,234,0.85)', fontSize: 15, padding: '4px 0', lineHeight: 1.5}}>
              Tøndervej 239<br/>6280 Højer
            </div>
          </div>
        </div>
        <div className="footer-bottom">
          <div>© 2026 Emmerske Efterskole</div>
          <div style={{display: 'flex', gap: 24}}>
            <a href="#" style={{display: 'inline', padding: 0}}>Cookies</a>
            <a href="#" style={{display: 'inline', padding: 0}}>Tilgængelighed</a>
            <a href="#" style={{display: 'inline', padding: 0}}>Persondata</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

// ========== TWEAKS PANEL ==========
function TweaksPanel({ tweaks, setTweaks }) {
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    const onMsg = (e) => {
      if (e.data?.type === '__activate_edit_mode') setVisible(true);
      if (e.data?.type === '__deactivate_edit_mode') setVisible(false);
    };
    window.addEventListener('message', onMsg);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', onMsg);
  }, []);

  const update = (k, v) => {
    const next = { ...tweaks, [k]: v };
    setTweaks(next);
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [k]: v } }, '*');
  };

  if (!visible) return null;
  return (
    <div className="tweaks-panel">
      <h4>Tweaks</h4>
      <div className="tweak-row">
        <label>Hero-variant</label>
        <select value={tweaks.heroVariant} onChange={e => update('heroVariant', e.target.value)}>
          <option value="collage">Fotocollage + video</option>
          <option value="fullvideo">Stort videovindue</option>
          <option value="audio">Lyd-først (podcast)</option>
        </select>
      </div>
      <div className="tweak-row">
        <label>Ledige-pladser stil</label>
        <select value={tweaks.spotsStyle} onChange={e => update('spotsStyle', e.target.value)}>
          <option value="bar">Banner øverst</option>
          <option value="floating">Flydende badge</option>
          <option value="none">Skjult</option>
        </select>
      </div>
      <div className="tweak-row">
        <label>Farvetema</label>
        <select value={tweaks.theme} onChange={e => update('theme', e.target.value)}>
          <option value="default">Grøn + sol (Pantone 341)</option>
          <option value="warm">Grøn + coral</option>
          <option value="soft">Blød grøn + creme</option>
        </select>
      </div>
      <div className="tweak-row">
        <label>Tone</label>
        <select value={tweaks.tone} onChange={e => update('tone', e.target.value)}>
          <option value="du">Direkte 'du' til eleven</option>
          <option value="omsorg">Omsorgsfuld til forældre</option>
          <option value="ung">Ungt og legende</option>
        </select>
      </div>
    </div>
  );
}

Object.assign(window, { ListenChip, Topbar, A11yPanel, Footer, TweaksPanel });
