/* ============================================================
   MAISON ATLAS — shared React components (exported to window)
   ============================================================ */
const { useState, useEffect, useRef, useCallback } = React;
const T = (lang, key) => window.ATLAS.t(lang, key);

/* ---- language hook: applies dir + body class globally ---- */
function useLang() {
  const [lang, setLangState] = useState(window.ATLAS.getLang());
  useEffect(() => {
    const meta = window.ATLAS.langs.find(l => l.code === lang) || window.ATLAS.langs[0];
    document.documentElement.lang = lang;
    document.documentElement.dir = meta.dir;
    document.body.classList.toggle('lang-ar', lang === 'ar');
    window.ATLAS.setLang(lang);
  }, [lang]);
  return [lang, setLangState];
}

/* ---- Flag icons (clean geometric SVG, rounded) ---- */
function Flag({ code, size = 22 }) {
  const w = size, h = Math.round(size * 0.72), r = Math.max(2, size * 0.16);
  const wrap = (kids) => (
    <svg className="flag" width={w} height={h} viewBox="0 0 30 22" aria-hidden="true">
      <defs><clipPath id={'fc-' + code}><rect x="0" y="0" width="30" height="22" rx={r} ry={r} /></clipPath></defs>
      <g clipPath={'url(#fc-' + code + ')'}>{kids}</g>
      <rect x="0.5" y="0.5" width="29" height="21" rx={r} ry={r} fill="none" stroke="oklch(1 0 0 / 0.18)" />
    </svg>
  );
  const flags = {
    FR: <g><rect width="10" height="22" fill="#0b4ea2" /><rect x="10" width="10" height="22" fill="#fff" /><rect x="20" width="10" height="22" fill="#e1000f" /></g>,
    EN: <g><rect width="30" height="22" fill="#012169" /><path d="M0 0L30 22M30 0L0 22" stroke="#fff" strokeWidth="4" /><path d="M0 0L30 22M30 0L0 22" stroke="#c8102e" strokeWidth="2" /><path d="M15 0V22M0 11H30" stroke="#fff" strokeWidth="6" /><path d="M15 0V22M0 11H30" stroke="#c8102e" strokeWidth="3.4" /></g>,
    ES: <g><rect width="30" height="22" fill="#c60b1e" /><rect y="5.5" width="30" height="11" fill="#ffc400" /><circle cx="9" cy="11" r="1.7" fill="#c60b1e" /></g>,
    IT: <g><rect width="10" height="22" fill="#008c45" /><rect x="10" width="10" height="22" fill="#fff" /><rect x="20" width="10" height="22" fill="#cd212a" /></g>,
    DE: <g><rect width="30" height="7.34" fill="#000" /><rect y="7.34" width="30" height="7.34" fill="#dd0000" /><rect y="14.66" width="30" height="7.34" fill="#ffce00" /></g>,
    AR: <g><rect width="30" height="22" fill="#c1272d" /><path d="M15 7l1.2 3.6h3.8l-3.1 2.3 1.2 3.6-3.1-2.2-3.1 2.2 1.2-3.6-3.1-2.3h3.8z" fill="none" stroke="#006233" strokeWidth="1.1" /></g>,
  };
  return wrap(flags[code] || <rect width="30" height="22" fill="#888" />);
}

const LANG_NAMES = {
  FR: { fr: 'Français', en: 'French', ar: 'الفرنسية' },
  EN: { fr: 'Anglais', en: 'English', ar: 'الإنجليزية' },
  ES: { fr: 'Espagnol', en: 'Spanish', ar: 'الإسبانية' },
  IT: { fr: 'Italien', en: 'Italian', ar: 'الإيطالية' },
  DE: { fr: 'Allemand', en: 'German', ar: 'الألمانية' },
  AR: { fr: 'Arabe', en: 'Arabic', ar: 'العربية' },
};

/* ---- brand mark: multicolor Moroccan khatim rosette ---- */
function BrandMark({ size = 42 }) {
  return (
    <svg className="brand-svg" width={size} height={size} viewBox="0 0 44 44" aria-hidden="true">
      <g>
        {/* gold diamond → N/S/E/W points */}
        <rect x="7" y="7" width="30" height="30" rx="4" fill="var(--gold)" transform="rotate(45 22 22)" />
        {/* majorelle square → diagonal points + center */}
        <rect x="7" y="7" width="30" height="30" rx="4" fill="var(--majorelle)" />
        {/* terracotta ring diamond */}
        <rect x="13.5" y="13.5" width="17" height="17" rx="3" fill="var(--terracotta)" transform="rotate(45 22 22)" />
        {/* saffron bright center */}
        <rect x="15" y="15" width="14" height="14" rx="2.5" fill="var(--saffron)" />
        <circle cx="22" cy="22" r="2.4" fill="var(--majorelle)" />
      </g>
    </svg>
  );
}

function Logo({ lang, href = '#/' }) {
  return (
    <a href={href} className="brand-logo" aria-label="GoToMorocco">
      <BrandMark size={42} />
      <span className="brand-words">
        <span className="brand-name display"><span className="bw-a">GoTo</span><span className="bw-b">Morocco</span></span>
        <span className="brand-sub">{T(lang, 'brandSub')}</span>
      </span>
    </a>
  );
}

/* ---- currency switch ---- */
function CurrencySwitch({ lang }) {
  const [cur, setCur] = useState(window.ATLAS.getCurrency());
  const [open, setOpen] = useState(false);
  useEffect(() => window.ATLAS.subscribeCurrency(() => setCur(window.ATLAS.getCurrency())), []);
  const sym = (c) => lang === 'ar' ? c.symAr : c.sym;
  return (
    <div className="cur-switch">
      <button className="cur-btn" onClick={() => setOpen(o => !o)} aria-label={T(lang, 'cur_label')}>
        {cur}<span className="cur-caret">▾</span>
      </button>
      {open && (
        <div className="cur-drop" onMouseLeave={() => setOpen(false)}>
          {window.ATLAS.currencies.map(c => (
            <button key={c.code} className={c.code === cur ? 'on' : ''} onClick={() => { window.ATLAS.setCurrency(c.code); setOpen(false); }}>
              <span>{c.code}</span><span className="faint">{sym(c)}</span>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

/* ---- animated count-up (triggers when scrolled into view) ---- */
function CountUp({ end, suffix = '', dur = 1400 }) {
  const [v, setV] = useState(0);
  const ref = useRef(null); const started = useRef(false);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    const run = () => {
      if (started.current) return; started.current = true;
      const t0 = performance.now();
      const tick = (now) => { const p = Math.min(1, (now - t0) / dur); setV(Math.round(end * (1 - Math.pow(1 - p, 3)))); if (p < 1) requestAnimationFrame(tick); };
      requestAnimationFrame(tick);
    };
    const io = new IntersectionObserver((es) => es.forEach(e => { if (e.isIntersecting) run(); }), { threshold: 0.4 });
    io.observe(el); return () => io.disconnect();
  }, [end, dur]);
  return <span ref={ref}>{v}{suffix}</span>;
}

/* ---- TripAdvisor rating bubbles + mark ---- */
function RatingBubbles({ value = 5, size = 15 }) {
  return (
    <span className="ta-bubbles" style={{ '--bs': size + 'px' }}>
      {[0, 1, 2, 3, 4].map(i => {
        const cls = value >= i + 1 ? 'full' : value > i ? 'half' : 'empty';
        return <span key={i} className={'ta-bub ' + cls}></span>;
      })}
    </span>
  );
}
function TripAdvisorMark({ small }) {
  return (
    <span className={'ta-logo' + (small ? ' sm' : '')}>
      <span className="ta-owl"><span className="eye"></span><span className="eye"></span></span>
      <span className="ta-word">Tripadvisor</span>
    </span>
  );
}

/* ---- language switch ---- */
function LangSwitch({ lang, setLang, compact }) {
  const [open, setOpen] = useState(false);
  const cur = window.ATLAS.langs.find(l => l.code === lang) || window.ATLAS.langs[0];
  if (compact) {
    // inline pills (used in mobile menu)
    return (
      <div className="lang-pills">
        {window.ATLAS.langs.map(l => (
          <button key={l.code} className={'lang-pill' + (l.code === lang ? ' active' : '')} onClick={() => setLang(l.code)}>
            <Flag code={l.flag} size={18} /><span>{l.label}</span>
          </button>
        ))}
      </div>
    );
  }
  return (
    <div className="lang-switch">
      <button className="lang-trigger" onClick={() => setOpen(o => !o)} aria-label="Language">
        <Flag code={cur.flag} size={20} />
        <span className="lt-label">{cur.label}</span>
        <span className="cur-caret">▾</span>
      </button>
      {open && (
        <div className="lang-drop" onMouseLeave={() => setOpen(false)}>
          {window.ATLAS.langs.map(l => (
            <button key={l.code} className={'lang-opt' + (l.code === lang ? ' on' : '')}
              onClick={() => { setLang(l.code); setOpen(false); }}>
              <Flag code={l.flag} size={20} /><span>{l.name}</span>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

/* ---- status badge ---- */
function StatusBadge({ status, lang }) {
  const map = {
    pending: 'pending', confirmed: 'confirmed', progress: 'progress', done: 'done', refused: 'refused',
  };
  return (
    <span className={'badge ' + (map[status] || 'pending')}>
      <span className="dot"></span>{T(lang, 'st_' + status)}
    </span>
  );
}

/* ---- vehicle photo slot (persists across pages via shared id) ---- */
function VehicleSlot({ vehId, lang, height = 200, radius = 14 }) {
  const ref = useRef(null);
  useEffect(() => {
    if (ref.current) {
      ref.current.setAttribute('id', 'veh-' + vehId);
      ref.current.setAttribute('shape', 'rounded');
      ref.current.setAttribute('radius', String(radius));
      ref.current.setAttribute('placeholder', T(lang, 'veh_' + vehId + '_t'));
      var _src = window.ATLAS.photo('veh-' + vehId);
      if (_src) ref.current.setAttribute('src', _src);
      ref.current.style.width = '100%';
      ref.current.style.height = height + 'px';
    }
  }, [vehId, lang, height, radius]);
  return React.createElement('image-slot', { ref });
}

/* ---- small inline icon set (geometric only) ---- */
function Ic({ name, size = 18 }) {
  const s = { width: size, height: size, display: 'block' };
  const sw = 1.6;
  const common = { fill: 'none', stroke: 'currentColor', strokeWidth: sw, strokeLinecap: 'round', strokeLinejoin: 'round' };
  const paths = {
    arrow: <path d="M5 12h14M13 6l6 6-6 6" {...common} />,
    check: <path d="M5 12l5 5L19 7" {...common} />,
    x: <path d="M6 6l12 12M18 6L6 18" {...common} />,
    user: <g {...common}><circle cx="12" cy="8" r="3.4" /><path d="M5 20c0-3.6 3.1-6 7-6s7 2.4 7 6" /></g>,
    pin: <g {...common}><path d="M12 21s7-5.6 7-11a7 7 0 10-14 0c0 5.4 7 11 7 11z" /><circle cx="12" cy="10" r="2.4" /></g>,
    cal: <g {...common}><rect x="4" y="5" width="16" height="16" rx="2" /><path d="M4 9h16M8 3v4M16 3v4" /></g>,
    clock: <g {...common}><circle cx="12" cy="12" r="8" /><path d="M12 8v4l3 2" /></g>,
    users: <g {...common}><circle cx="9" cy="8" r="3" /><path d="M3 19c0-3 2.7-5 6-5s6 2 6 5" /><path d="M16 6a3 3 0 010 6M21 19c0-2.4-1.6-4.2-4-4.8" /></g>,
    car: <g {...common}><path d="M5 16l1.5-5.5A2 2 0 018.4 9h7.2a2 2 0 011.9 1.5L19 16" /><rect x="3" y="16" width="18" height="3.2" rx="1" /><circle cx="7.5" cy="19" r="0" /></g>,
    chat: <g {...common}><path d="M4 5h16v11H8l-4 4z" /></g>,
    send: <path d="M4 12l16-7-7 16-2.5-6.5z" {...common} />,
    search: <g {...common}><circle cx="11" cy="11" r="6" /><path d="M20 20l-4-4" /></g>,
    money: <g {...common}><rect x="3" y="6" width="18" height="12" rx="2" /><circle cx="12" cy="12" r="2.6" /></g>,
    grid: <g {...common}><rect x="4" y="4" width="7" height="7" rx="1.5" /><rect x="13" y="4" width="7" height="7" rx="1.5" /><rect x="4" y="13" width="7" height="7" rx="1.5" /><rect x="13" y="13" width="7" height="7" rx="1.5" /></g>,
    list: <g {...common}><path d="M8 6h12M8 12h12M8 18h12M4 6h.01M4 12h.01M4 18h.01" /></g>,
    bag: <g {...common}><path d="M6 8h12l-1 12H7L6 8z" /><path d="M9 8V6a3 3 0 016 0v2" /></g>,
    star: <path d="M12 4l2.3 4.7 5.2.8-3.8 3.7.9 5.2-4.6-2.4-4.6 2.4.9-5.2L4.5 9.5l5.2-.8z" {...common} />,
    globe: <g {...common}><circle cx="12" cy="12" r="8" /><path d="M4 12h16M12 4c2.5 2.5 2.5 13 0 16M12 4c-2.5 2.5-2.5 13 0 16" /></g>,
    plane: <path d="M10 5l9 7-9 7v-4l-6-3 6-3z" {...common} />,
    plus: <path d="M12 5v14M5 12h14" {...common} />,
    phone: <path d="M6 4h3l2 5-2 1.5a11 11 0 005 5L15 13l5 2v3a2 2 0 01-2 2A14 14 0 014 6a2 2 0 012-2z" {...common} />,
  };
  return <svg viewBox="0 0 24 24" style={s} aria-hidden="true">{paths[name] || null}</svg>;
}

Object.assign(window, { useLang, BrandMark, Logo, LangSwitch, CurrencySwitch, CountUp, RatingBubbles, TripAdvisorMark, StatusBadge, VehicleSlot, Ic, T, Flag, LANG_NAMES });
