/* YeYe Portal — UI primitives (React + Babel) */
const { useState, useEffect, useLayoutEffect, useRef, useMemo } = React;

/* ---------- Icon (Lucide) ---------- */
const _pascal = (n) => n.replace(/(^|-)([a-z0-9])/g, (_, __, c) => c.toUpperCase());
const NS = 'http://www.w3.org/2000/svg';
function addShapes(svg, node) {
  if (!Array.isArray(node)) return;
  if (typeof node[0] === 'string') {
    const tag = node[0];
    const attrs = (node[1] && typeof node[1] === 'object') ? node[1] : {};
    const el = document.createElementNS(NS, tag);
    for (const k in attrs) el.setAttribute(k, attrs[k]);
    svg.appendChild(el);
    if (Array.isArray(node[2])) node[2].forEach((c) => addShapes(el, c));
  } else {
    node.forEach((c) => addShapes(svg, c));
  }
}
function buildIcon(node, size, stroke) {
  const svg = document.createElementNS(NS, 'svg');
  const set = (a, b) => svg.setAttribute(a, b);
  set('viewBox', '0 0 24 24'); set('width', size); set('height', size);
  set('fill', 'none'); set('stroke', 'currentColor'); set('stroke-width', stroke);
  set('stroke-linecap', 'round'); set('stroke-linejoin', 'round');
  addShapes(svg, node);
  return svg;
}
function Icon({ name, size = 18, stroke = 2, className = '', style }) {
  const ref = useRef(null);
  useLayoutEffect(() => {
    const host = ref.current; if (!host) return;
    const L = window.lucide; let node = null;
    if (L && L.icons) node = L.icons[_pascal(name)] || L.icons[name];
    host.innerHTML = '';
    if (node) host.appendChild(buildIcon(node, size, stroke));
  }, [name, size, stroke]);
  return <span ref={ref} className={'ic ' + className} style={{ display: 'inline-flex', width: size, height: size, ...style }} />;
}

/* ---------- Button ---------- */
function Btn({ variant = 'ghost', size, icon, iconR, children, className = '', ...p }) {
  const cls = ['btn', 'btn-' + variant, size === 'sm' ? 'btn-sm' : size === 'lg' ? 'btn-lg' : '', className].join(' ');
  const spinClass = (name) => /^loader($|-)/.test(String(name || '')) ? 'spin' : '';
  return (
    <button className={cls} {...p}>
      {icon && <Icon name={icon} size={size === 'sm' ? 14 : 16} className={spinClass(icon)} />}
      {children}
      {iconR && <Icon name={iconR} size={size === 'sm' ? 14 : 16} className={spinClass(iconR)} />}
    </button>
  );
}
function IconBtn({ name, className = '', dot, ...p }) {
  return <button className={'icon-btn ' + className} {...p}><Icon name={name} size={19} />{dot && <i className="dot" />}</button>;
}

/* ---------- Card ---------- */
function Card({ children, className = '', ...p }) { return <div className={'card ' + className} {...p}>{children}</div>; }
function CardHead({ icon, title, sub, action }) {
  return (
    <div className="card-hd">
      {icon && <div className="hd-ic"><Icon name={icon} size={17} /></div>}
      <div className="hd-tx"><div className="t">{title}</div>{sub && <div className="s">{sub}</div>}</div>
      {action}
    </div>
  );
}

/* ---------- Badge ---------- */
const STMAP = { ok: 'b-ok', warn: 'b-warn', bad: 'b-bad', info: 'b-info', neut: 'b-neut', brand: 'b-brand' };
function Badge({ tone = 'neut', dot, children }) {
  return <span className={'badge ' + (STMAP[tone] || 'b-neut')}>{dot && <i className="bdot" />}{children}</span>;
}

/* ---------- Segmented ---------- */
function Seg({ items, value, onChange }) {
  return (
    <div className="seg">
      {items.map((it) => (
        <button key={it.value} className={value === it.value ? 'on' : ''} onClick={() => onChange(it.value)}>
          {it.label}
        </button>
      ))}
    </div>
  );
}

/* ---------- Avatar ---------- */
function Avatar({ children, size = 'md', tone, src }) {
  const st = tone ? { background: tone.bg, color: tone.fg } : undefined;
  return <div className={'avatar a-' + size} style={st}>{src ? <img src={src} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : children}</div>;
}

/* ---------- Progress ---------- */
function Progress({ value, thin }) {
  return <div className={'prog ' + (thin ? 'thin' : '')}><span style={{ width: Math.max(2, value) + '%' }} /></div>;
}

/* ---------- Steps (horizontal) ---------- */
function Steps({ steps }) {
  return (
    <div className="steps">
      {steps.map((s, i) => (
        <div key={i} className={'step ' + s.state}>
          <div className="sline" />
          <div className="snode">{s.state === 'done' ? <Icon name="check" size={15} stroke={3} /> : i + 1}</div>
          <div className="slab">{s.label}</div>
        </div>
      ))}
    </div>
  );
}

/* ---------- Stat tile ---------- */
function Stat({ icon, tone = '', value, label, trend, trendDir }) {
  return (
    <div className="stat">
      <div className="st-top">
        <div className={'st-ic ' + tone}><Icon name={icon} size={18} /></div>
        {trend && <span className={'trend ' + (trendDir || 'up')}><Icon name={trendDir === 'down' ? 'trending-down' : 'trending-up'} size={14} stroke={2.4} />{trend}</span>}
      </div>
      <div><div className="st-val tnum">{value}</div><div className="st-lab">{label}</div></div>
    </div>
  );
}

/* ---------- Alert ---------- */
function Alert({ tone = 'info', icon, title, children, action }) {
  const ic = icon || (tone === 'bad' ? 'octagon-alert' : tone === 'warn' ? 'triangle-alert' : tone === 'ok' ? 'check' : 'info');
  return (
    <div className={'alert ' + tone}>
      <div className="a-ic"><Icon name={ic} size={16} /></div>
      <div className="grow"><div className="a-t">{title}</div>{children && <div className="a-s">{children}</div>}</div>
      {action}
    </div>
  );
}

/* ---------- Toggle ---------- */
function Toggle({ on, onChange }) { return <button className={'toggle ' + (on ? 'on' : '')} onClick={() => onChange(!on)} aria-pressed={on} />; }

/* ---------- Field ---------- */
function Field({ label, children }) { return <label className="field">{label && <span>{label}</span>}{children}</label>; }

/* ---------- Modal ---------- */
function Modal({ title, icon, sub, onClose, children, footer, wide }) {
  const dialogRef = useRef(null);
  const onCloseRef = useRef(onClose);
  onCloseRef.current = onClose;
  useEffect(() => {
    const dialog = dialogRef.current;
    const previousFocus = document.activeElement;
    const focusable = () => dialog ? Array.from(dialog.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), iframe, [tabindex]:not([tabindex="-1"])')) : [];
    const first = focusable()[0];
    if (first) first.focus();
    else if (dialog) dialog.focus();
    const h = (e) => {
      if (e.key === 'Escape') { onCloseRef.current(); return; }
      if (e.key !== 'Tab') return;
      const items = focusable();
      if (!items.length) { e.preventDefault(); return; }
      const firstItem = items[0];
      const lastItem = items[items.length - 1];
      if (e.shiftKey && document.activeElement === firstItem) { e.preventDefault(); lastItem.focus(); }
      else if (!e.shiftKey && document.activeElement === lastItem) { e.preventDefault(); firstItem.focus(); }
    };
    window.addEventListener('keydown', h);
    return () => {
      window.removeEventListener('keydown', h);
      if (previousFocus && previousFocus.focus) previousFocus.focus();
    };
  }, []);
  return (
    <div className="overlay" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
      <div ref={dialogRef} className={'modal ' + (wide ? 'wide' : '')} role="dialog" aria-modal="true" aria-label={title} tabIndex="-1">
        <div className="modal-hd">
          {icon && <div className="hd-ic"><Icon name={icon} size={18} /></div>}
          <div className="grow"><div className="h3">{title}</div>{sub && <div className="muted" style={{ fontSize: 12.5 }}>{sub}</div>}</div>
          <IconBtn name="x" onClick={onClose} />
        </div>
        <div className="modal-bd">{children}</div>
        {footer && <div className="modal-ft">{footer}</div>}
      </div>
    </div>
  );
}

/* ---------- Right panel ---------- */
function Panel({ title, onClose, children, footer }) {
  return (
    <>
      <div className="scrim show" onClick={onClose} style={{ zIndex: 89 }} />
      <div className="panel">
        <div className="modal-hd"><div className="grow"><div className="h3">{title}</div></div><IconBtn name="x" onClick={onClose} /></div>
        <div className="modal-bd grow" style={{ flex: 1 }}>{children}</div>
        {footer && <div className="modal-ft">{footer}</div>}
      </div>
    </>
  );
}

/* ---------- Brand logo ---------- */
function BrandLogo({ mini }) {
  return (
    <div className="brand">
      {mini
        ? <img src="assets/yeye-mark.png" alt="YeYe" style={{ height: 30, width: 'auto', display: 'block' }} />
        : <img src="assets/yeye-logo.png" alt="YeYe Expats Centre" style={{ height: 30, width: 'auto', display: 'block' }} />}
      {!mini && <span style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: '.14em', textTransform: 'uppercase', color: 'var(--ink-400)', marginLeft: 2, alignSelf: 'flex-end', paddingBottom: 3 }}>Expats Centre</span>}
    </div>
  );
}
function BrandSlogan() {
  const { t } = useT();
  return <div className="brand-slogan">{t('brand.slogan')}</div>;
}

/* ---------- i18n context ---------- */
const LangCtx = React.createContext(null);
function useT() {
  const c = React.useContext(LangCtx);
  if (c) return c;
  return { lang: 'en', currency: 'EUR', setLang: () => {}, setCurrency: () => {}, t: (k) => (window.I18N.en[k] || k), dict: window.I18N.en };
}

/* ---------- Language menu ---------- */
function LangMenu({ lang, onChange }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', h); return () => document.removeEventListener('mousedown', h);
  }, []);
  const order = ['en', 'tr', 'cs'];
  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button className="icon-btn" onClick={() => setOpen((o) => !o)} title="Language"
        style={{ width: 'auto', padding: '0 10px', gap: 6, border: '1px solid var(--line)' }}>
        <Icon name="languages" size={17} />
        <span style={{ fontSize: 12.5, fontWeight: 700 }}>{window.I18N[lang].code}</span>
        <Icon name="chevron-down" size={14} />
      </button>
      {open && (
        <div style={{ position: 'absolute', top: 44, right: 0, background: '#fff', border: '1px solid var(--line)', borderRadius: 'var(--r-md)', boxShadow: 'var(--sh-lg)', padding: 6, width: 168, zIndex: 60 }}>
          {order.map((lk) => (
            <button key={lk} onClick={() => { onChange(lk); setOpen(false); }}
              className="flex ac jb" style={{ width: '100%', border: 'none', background: lang === lk ? 'var(--brand-50)' : 'transparent', borderRadius: 8, padding: '9px 11px', cursor: 'pointer' }}>
              <span className="flex ac gap-8" style={{ fontSize: 13.5, fontWeight: lang === lk ? 700 : 500, color: lang === lk ? 'var(--brand-700)' : 'var(--ink-700)' }}>
                <span className="mono" style={{ fontSize: 11, color: 'var(--ink-400)', width: 20 }}>{window.I18N[lk].code}</span>
                {window.I18N[lk].name}
              </span>
              {lang === lk && <Icon name="check" size={15} stroke={2.6} />}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

function CurrencyMenu({ currency, onChange }) {
  const { t } = useT();
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  const options = [
    { k: 'EUR', label: 'EUR', sub: '€' },
    { k: 'CZK', label: 'CZK', sub: 'Kč' },
    { k: 'TRY', label: 'TL', sub: '₺' },
  ];
  useEffect(() => {
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', h); return () => document.removeEventListener('mousedown', h);
  }, []);
  const active = options.find((x) => x.k === currency) || options[0];
  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button className="icon-btn" onClick={() => setOpen((o) => !o)} title={t('currency.title')}
        style={{ width: 'auto', padding: '0 10px', gap: 7, border: '1px solid var(--line)' }}>
        <Icon name="coins" size={17} />
        <span style={{ fontSize: 12.5, fontWeight: 700 }}>{active.label}</span>
      </button>
      {open && (
        <div className="menu-pop" style={{ position: 'absolute', right: 0, top: 42, width: 160, zIndex: 60 }}>
          <div style={{ padding: 6 }}>
            {options.map((opt) => (
              <button key={opt.k} type="button" onClick={() => { onChange(opt.k); setOpen(false); }}
                className="flex ac jb" style={{ width: '100%', border: 'none', background: currency === opt.k ? 'var(--brand-50)' : 'transparent', borderRadius: 8, padding: '9px 11px', cursor: 'pointer' }}>
                <span className="flex ac gap-8" style={{ fontSize: 13.5, fontWeight: currency === opt.k ? 700 : 500, color: currency === opt.k ? 'var(--brand-700)' : 'var(--ink-700)' }}>
                  <span className="mono" style={{ fontSize: 11, color: 'var(--ink-400)', width: 24 }}>{opt.sub}</span>
                  {opt.label}
                </span>
                {currency === opt.k && <Icon name="check" size={15} stroke={2.6} />}
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, {
  Icon, Btn, IconBtn, Card, CardHead, Badge, Seg, Avatar, Progress, Steps, Stat,
  Alert, Toggle, Field, Modal, Panel, BrandLogo, BrandSlogan, LangCtx, useT, LangMenu, CurrencyMenu,
  useState, useEffect, useRef, useMemo, useLayoutEffect,
});
