/* ============================================================
   egitimci-shared.jsx
   Tüm sayfalarda ortak kullanılan bileşenler
   ============================================================ */

const { useState, useEffect } = React;

/* ---------- Lucide ikonları (Nav için, mobile menüde gösterilir) ---------- */
const NAV_ICONS = {
  home: ['<path d="m3 9 9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>', '<polyline points="9 22 9 12 15 12 15 22"/>'],
  info: ['<circle cx="12" cy="12" r="10"/>', '<path d="M12 16v-4"/>', '<path d="M12 8h.01"/>'],
  layers: [
    '<path d="m12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83Z"/>',
    '<path d="m22 17.65-9.17 4.16a2 2 0 0 1-1.66 0L2 17.65"/>',
    '<path d="m22 12.65-9.17 4.16a2 2 0 0 1-1.66 0L2 12.65"/>'
  ],
  footprints: [
    '<path d="M4 16v-2.38C4 11.5 2.97 10.5 3 8c.03-2.72 1.49-6 4.5-6C9.37 2 10 3.8 10 5.5c0 3.11-2 5.66-2 8.68V16a2 2 0 1 1-4 0Z"/>',
    '<path d="M20 20v-2.38c0-2.12 1.03-3.12 1-5.62-.03-2.72-1.49-6-4.5-6C14.63 6 14 7.8 14 9.5c0 3.11 2 5.66 2 8.68V20a2 2 0 1 0 4 0Z"/>',
    '<path d="M16 17h4"/>', '<path d="M4 13h4"/>'
  ],
  users: [
    '<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/>',
    '<circle cx="9" cy="7" r="4"/>',
    '<path d="M22 21v-2a4 4 0 0 0-3-3.87"/>',
    '<path d="M16 3.13a4 4 0 0 1 0 7.75"/>'
  ],
  bookOpen: [
    '<path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"/>',
    '<path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"/>'
  ],
  graduationCap: [
    '<path d="M21.42 10.922a1 1 0 0 0-.019-1.838L12.83 5.18a2 2 0 0 0-1.66 0L2.6 9.08a1 1 0 0 0 0 1.832l8.57 3.908a2 2 0 0 0 1.66 0z"/>',
    '<path d="M22 10v6"/>',
    '<path d="M6 12.5V16a6 3 0 0 0 12 0v-3.5"/>'
  ],
  helpCircle: [
    '<circle cx="12" cy="12" r="10"/>',
    '<path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/>',
    '<path d="M12 17h.01"/>'
  ],
  mail: [
    '<rect width="20" height="16" x="2" y="4" rx="2"/>',
    '<path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"/>'
  ]
};

function navIcon(name) {
  const paths = NAV_ICONS[name];
  if (!paths) return null;
  return React.createElement('svg', {
    className: 'nav-icon',
    width: 18, height: 18, viewBox: '0 0 24 24',
    fill: 'none', stroke: 'currentColor', strokeWidth: 1.75,
    strokeLinecap: 'round', strokeLinejoin: 'round',
    'aria-hidden': 'true',
    dangerouslySetInnerHTML: { __html: paths.join('') }
  });
}

/* ---------- Img component (graceful fallback) ---------- */
function Img({ src, alt, className = '', placeholder = '' }) {
  const [errored, setErrored] = useState(false);

  if (!src || errored) {
    return (
      React.createElement('div', {
        className: `ph ${className}`,
        role: 'img',
        'aria-label': alt || 'görsel'
      }, placeholder || alt || 'görsel')
    );
  }

  return React.createElement('img', {
    src,
    alt: alt || '',
    className,
    onError: () => setErrored(true),
    loading: 'lazy'
  });
}

/* ---------- Nav ---------- */
function Nav({ active = '' }) {
  const [open, setOpen] = useState(false);
  // Mobile akordeon: aktif sayfa destek alanından biri ise (active==='destek')
  // hamburger açıldığında dropdown otomatik açık başlasın.
  const [destekOpen, setDestekOpen] = useState(active === 'destek');
  const [akademiOpen, setAkademiOpen] = useState(active === 'akademi');

  // Menü tıklamasında mobil menü kapansın
  useEffect(() => {
    const close = () => setOpen(false);
    window.addEventListener('hashchange', close);
    return () => window.removeEventListener('hashchange', close);
  }, []);

  const items = [
    { href: 'index.html',                key: 'ana',         icon: 'home',          label: 'Ana Sayfa' },
    { href: 'hakkimizda.html',           key: 'hakkimizda',  icon: 'info',          label: 'Hakkımızda' },
    {
      key: 'destek',
      icon: 'layers',
      label: 'Destek Alanlarımız',
      dropdown: [
        { href: 'dil-konusma.html',       label: 'Dil-Konuşma' },
        { href: 'oges.html',              label: 'Öğrenme Güçlüğü' },
        { href: 'zihin-yetersizligi.html', label: 'Zihinsel Destek' },
        { href: 'otizm.html',             label: 'Otizm Spektrum' },
      ]
    },
    { href: 'surec.html',                key: 'surec',        icon: 'footprints',    label: 'Süreç' },
    { href: 'kadro.html',                key: 'kadro',        icon: 'users',         label: 'Kadro' },
    {
      key: 'akademi',
      icon: 'graduationCap',
      label: 'Akademi',
      dropdown: [
        { href: 'akademi.html#aileler',         label: 'Aileler İçin' },
        { href: 'akademi.html#meslektaslar',    label: 'Meslektaşlar İçin' },
        { href: 'cocuk-gelisim-tarama-testi.html', label: 'Tarama Testi (EGTR)' },
      ]
    },
    { href: 'sss.html',                  key: 'sss',          icon: 'helpCircle',    label: 'SSS' },
    { href: 'veli-rehberi.html',         key: 'veli',         icon: 'bookOpen',      label: 'Veli Rehberi' },
    { href: 'iletisim.html',             key: 'iletisim',     icon: 'mail',          label: 'İletişim' },
  ];

  return React.createElement('nav', { className: 'nav', 'aria-label': 'ana menü' },
    React.createElement('div', { className: 'nav-inner' },
      // Marka
      React.createElement('a', { href: 'index.html', className: 'nav-brand', 'aria-label': 'Eğitimci ana sayfa' },
        React.createElement('img', { src: 'images/logo.svg', alt: 'Eğitimci logosu' }),
        React.createElement('div', null,
          React.createElement('div', { className: 'nav-brand-text' }, 'Eğitimci'),
          React.createElement('div', { className: 'nav-brand-sub' }, 'dil konuşma')
        )
      ),
      // Mobil hamburger
      React.createElement('button', {
        className: 'nav-toggle',
        'aria-label': open ? 'menüyü kapat' : 'menüyü aç',
        'aria-expanded': open,
        onClick: () => setOpen(!open)
      },
        React.createElement('svg', { width: 24, height: 24, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 2 },
          open
            ? React.createElement('path', { d: 'M6 6L18 18M6 18L18 6' })
            : React.createElement('path', { d: 'M3 6h18M3 12h18M3 18h18' })
        )
      ),
      // Menü
      React.createElement('ul', { className: `nav-menu ${open ? 'open' : ''}` },
        items.map(item => {
          if (item.dropdown) {
            const isOpen = item.key === 'akademi' ? akademiOpen : destekOpen;
            const toggle = item.key === 'akademi' ? setAkademiOpen : setDestekOpen;
            return React.createElement('li', {
              key: item.key,
              className: 'has-dropdown' + (isOpen ? ' is-open' : '')
            },
              React.createElement('a', {
                href: '#',
                'aria-expanded': isOpen,
                'aria-haspopup': 'true',
                onClick: (e) => { e.preventDefault(); toggle(o => !o); }
              },
                navIcon(item.icon),
                React.createElement('span', { className: 'has-dropdown-label' }, item.label),
                React.createElement('svg', {
                  className: 'has-dropdown-chevron',
                  width: 18, height: 18, viewBox: '0 0 24 24',
                  fill: 'none', stroke: 'currentColor', strokeWidth: 2,
                  strokeLinecap: 'round', strokeLinejoin: 'round',
                  'aria-hidden': 'true'
                },
                  React.createElement('path', { d: 'm6 9 6 6 6-6' })
                )
              ),
              React.createElement('ul', { className: 'nav-dropdown' },
                item.dropdown.map(d =>
                  React.createElement('li', { key: d.href },
                    React.createElement('a', { href: d.href }, d.label)
                  )
                )
              )
            );
          }
          return React.createElement('li', { key: item.key },
            React.createElement('a', {
              href: item.href,
              className: active === item.key ? 'is-active' : '',
              'aria-current': active === item.key ? 'page' : undefined
            },
              navIcon(item.icon),
              React.createElement('span', null, item.label)
            )
          );
        })
      )
    )
  );
}

/* ---------- Footer ---------- */
function FooterEl() {
  const year = new Date().getFullYear();
  return React.createElement('footer', { className: 'footer' },
    React.createElement('div', { className: 'container' },
      React.createElement('div', { className: 'footer-grid' },
        // Marka
        React.createElement('div', null,
          React.createElement('span', { className: 'footer-brand' }, 'EĞİTİMCİ'),
          React.createElement('div', { className: 'footer-tagline' }, 'sözünüzü dinliyoruz.'),
          React.createElement('p', null, 'Eğitimci Dil Konuşma Özel Eğitim ve Rehabilitasyon Merkezi'),
          React.createElement('p', { className: 'mt-2' }, 'Bursa, Türkiye')
        ),
        // Hizmetler
        React.createElement('div', null,
          React.createElement('h4', null, 'Destek Alanları'),
          React.createElement('ul', { className: 'footer-links' },
            React.createElement('li', null, React.createElement('a', { href: 'dil-konusma.html' }, 'Dil-Konuşma')),
            React.createElement('li', null, React.createElement('a', { href: 'oges.html' }, 'Öğrenme Güçlüğü')),
            React.createElement('li', null, React.createElement('a', { href: 'zihin-yetersizligi.html' }, 'Zihinsel Destek')),
            React.createElement('li', null, React.createElement('a', { href: 'otizm.html' }, 'Otizm Spektrum'))
          )
        ),
        // Kurumsal
        React.createElement('div', null,
          React.createElement('h4', null, 'Kurum'),
          React.createElement('ul', { className: 'footer-links' },
            React.createElement('li', null, React.createElement('a', { href: 'hakkimizda.html' }, 'Hakkımızda')),
            React.createElement('li', null, React.createElement('a', { href: 'kadro.html' }, 'Kadro')),
            React.createElement('li', null, React.createElement('a', { href: 'akademi.html' }, 'Akademi')),
            React.createElement('li', null, React.createElement('a', { href: 'iletisim.html' }, 'İletişim'))
          )
        ),
        // Veli
        React.createElement('div', null,
          React.createElement('h4', null, 'Veliler İçin'),
          React.createElement('ul', { className: 'footer-links' },
            React.createElement('li', null, React.createElement('a', { href: 'cocuk-gelisim-tarama-testi.html' }, 'Tarama Testi (EGTR)')),
            React.createElement('li', null, React.createElement('a', { href: 'surec.html' }, 'Süreç')),
            React.createElement('li', null, React.createElement('a', { href: 'veli-rehberi.html' }, 'Veli Rehberi')),
            React.createElement('li', null, React.createElement('a', { href: 'sss.html' }, 'Sıkça Sorulanlar')),
            React.createElement('li', null, React.createElement('a', { href: 'iletisim.html#randevu' }, 'Randevu Al'))
          )
        )
      ),
      React.createElement('div', { className: 'footer-bottom' },
        React.createElement('div', null, `© ${year} Eğitimci Dil Konuşma Özel Eğitim ve Rehabilitasyon Merkezi`),
        React.createElement('a', { href: 'https://mavimine.com', className: 'footer-cross-link', target: '_blank', rel: 'noopener' },
          'çözüm ortağımız: Mavi Mine →'
        )
      )
    )
  );
}

/* ---------- Mini "Bunları da bilmek isteyebilirsiniz" şeridi ---------- */
function TipsStrip({ tips }) {
  if (!tips || tips.length === 0) return null;
  return React.createElement('section', { className: 'section section-sm bg-paper' },
    React.createElement('div', { className: 'container' },
      React.createElement('div', { className: 'eyebrow mb-3' }, 'bunları da bilmek isteyebilirsiniz'),
      React.createElement('div', { className: 'tips-strip' },
        tips.map((t, i) =>
          React.createElement('a', { key: i, href: t.href, className: 'tip-card' },
            t.icon && React.createElement('div', { className: 'tip-icon' }, t.icon),
            React.createElement('h4', null, t.title),
            t.text && React.createElement('p', null, t.text)
          )
        )
      )
    )
  );
}

/* ---------- ScrollTopButton — uzun sayfalarda yukarı çık butonu ---------- */
function ScrollTopButton() {
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    const onScroll = () => setVisible(window.scrollY > 400);
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const handleClick = () => window.scrollTo({ top: 0, behavior: 'smooth' });

  return React.createElement('button', {
    type: 'button',
    className: 'scroll-top-btn' + (visible ? ' is-visible' : ''),
    onClick: handleClick,
    'aria-label': 'Sayfa başına dön',
    title: 'Yukarı çık'
  },
    React.createElement('svg', {
      width: 24, height: 24, viewBox: '0 0 24 24',
      fill: 'none', stroke: 'currentColor', strokeWidth: 2.25,
      strokeLinecap: 'round', strokeLinejoin: 'round',
      'aria-hidden': 'true',
      dangerouslySetInnerHTML: { __html: '<path d="m18 15-6-6-6 6"/>' }
    })
  );
}

/* ---------- WhatsAppFloat — niyet seçici popup (tüm sayfalarda) ---------- */
const WHATSAPP_NUMARA = '905053058099'; // 0 505 305 80 99 — Halef

const WHATSAPP_NIYETLER = [
  {
    id: 'tanisma',
    icon: '☕',
    baslik: 'Tanışmak istiyorum',
    aciklama: 'Kurumu yakından görmek için',
    metin: 'Merhaba, Eğitimci Dil Konuşma Merkezi\'ni yakından tanımak için randevu almak istiyorum.'
  },
  {
    id: 'kayit',
    icon: '📋',
    baslik: 'RAM raporum var, kayıt yaptırmak istiyorum',
    aciklama: 'Doğrudan ön kayıt görüşmesi',
    metin: 'Merhaba, RAM raporlu çocuğum için ön kayıt görüşmesi yapmak istiyorum.'
  },
  {
    id: 'degerlendirme',
    icon: '🌱',
    baslik: 'Çocuğumu değerlendirmenizi istiyorum',
    aciklama: 'Tarama veya gözlem talebi',
    metin: 'Merhaba, çocuğumun gelişimi için bir değerlendirme talep etmek istiyorum.'
  },
  {
    id: 'ozel_seans',
    icon: '📚',
    baslik: 'RAM raporsuz özel seans bilgisi',
    aciklama: 'Raporum yok, seçeneklerim neler?',
    metin: 'Merhaba, RAM raporu olmadan özel seans seçenekleri hakkında bilgi almak istiyorum.'
  },
  {
    id: 'baska',
    icon: '✏️',
    baslik: 'Başka bir konu',
    aciklama: 'Mesajımı kendim yazayım',
    metin: ''
  }
];

function WhatsAppFloat() {
  const [acik, setAcik] = useState(false);

  const handleNiyetSec = (niyet) => {
    const encodedMetin = encodeURIComponent(niyet.metin);
    const url = 'https://wa.me/' + WHATSAPP_NUMARA + (encodedMetin ? '?text=' + encodedMetin : '');
    window.open(url, '_blank');
    setAcik(false);
  };

  return React.createElement(React.Fragment, null,
    React.createElement('button', {
      type: 'button',
      className: 'whatsapp-float' + (acik ? ' acik' : ''),
      onClick: () => setAcik(!acik),
      'aria-label': 'WhatsApp ile iletişim',
      'aria-expanded': acik
    },
      acik
        ? React.createElement('span', { className: 'whatsapp-close' }, '✕')
        : React.createElement('img', {
            src: 'images/whatsapp-icon.svg',
            alt: '',
            onError: (e) => {
              e.target.outerHTML = '<span style="font-size:28px">💬</span>';
            }
          })
    ),

    acik && React.createElement('div', {
      className: 'whatsapp-popup',
      onClick: (e) => {
        if (e.target === e.currentTarget) setAcik(false);
      }
    },
      React.createElement('div', { className: 'whatsapp-popup-card' },
        React.createElement('div', { className: 'whatsapp-popup-header' },
          React.createElement('h4', null, 'Merhaba! 👋'),
          React.createElement('p', null, 'Hangi konuda iletişim kurmak istiyorsunuz?'),
          React.createElement('button', {
            type: 'button',
            className: 'whatsapp-popup-close',
            onClick: () => setAcik(false),
            'aria-label': 'Kapat'
          }, '✕')
        ),
        React.createElement('div', { className: 'whatsapp-popup-list' },
          WHATSAPP_NIYETLER.map(niyet =>
            React.createElement('button', {
              key: niyet.id,
              type: 'button',
              className: 'whatsapp-niyet',
              onClick: () => handleNiyetSec(niyet)
            },
              React.createElement('span', { className: 'whatsapp-niyet-icon' }, niyet.icon),
              React.createElement('span', { className: 'whatsapp-niyet-icerik' },
                React.createElement('span', { className: 'whatsapp-niyet-baslik' }, niyet.baslik),
                React.createElement('span', { className: 'whatsapp-niyet-aciklama' }, niyet.aciklama)
              ),
              React.createElement('span', { className: 'whatsapp-niyet-arrow' }, '→')
            )
          )
        )
      )
    )
  );
}

/* ============================================================
   Supabase helper — form submit için
   ============================================================ */
async function submitToSupabase(table, payload) {
  const url = window.SUPABASE_URL;
  const key = window.SUPABASE_ANON_KEY;

  if (!url || !key) {
    throw new Error('Supabase config eksik');
  }

  const response = await fetch(url + '/rest/v1/' + table, {
    method: 'POST',
    headers: {
      'apikey': key,
      'Authorization': 'Bearer ' + key,
      'Content-Type': 'application/json',
      'Prefer': 'return=representation'
    },
    body: JSON.stringify(payload)
  });

  if (!response.ok) {
    const errText = await response.text();
    throw new Error('Supabase hatası: ' + response.status + ' — ' + errText);
  }

  // return=representation ile yaratılan satır body'de geliyor; Supabase array döner — ilk elemanı al.
  const data = await response.json();
  return Array.isArray(data) ? data[0] : data;
}

// Supabase'den tek bir kayıt çek (id ile)
async function fetchFromSupabase(table, id) {
  const url = window.SUPABASE_URL;
  const key = window.SUPABASE_ANON_KEY;
  if (!url || !key) {
    throw new Error('Supabase yapılandırması eksik');
  }
  try {
    const response = await fetch(url + '/rest/v1/' + table + '?id=eq.' + encodeURIComponent(id) + '&select=*', {
      method: 'GET',
      headers: {
        'apikey': key,
        'Authorization': 'Bearer ' + key,
        'Accept': 'application/json'
      }
    });
    if (!response.ok) {
      const errorText = await response.text();
      console.error('Supabase fetch error:', errorText);
      throw new Error('Supabase hatası: ' + response.status + ' — ' + errorText);
    }
    const data = await response.json();
    // PostgREST array dönüyor; tek kayıt arıyoruz
    if (!Array.isArray(data) || data.length === 0) {
      return null;  // kayıt bulunamadı
    }
    return data[0];
  } catch (err) {
    console.error('Supabase fetch exception:', err);
    throw err;
  }
}

window.fetchFromSupabase = fetchFromSupabase;
