/* Components.jsx — shared chrome + primitives
   Exports to window so other JSX files can use them. */

const { useState, useEffect, useRef, useContext, createContext, useCallback } = React;

// -------------------- Language --------------------
const LangContext = createContext({ lang: 'ar', setLang: () => {} });
const useLang = () => useContext(LangContext);
const t = (en, ar) => {
  const { lang } = useLang();
  return lang === 'ar' ? ar : en;
};

function LangProvider({ children }) {
  const [lang, setLang] = useState(() => localStorage.getItem('amu-lang') || 'ar');
  useEffect(() => {
    document.documentElement.dir = lang === 'ar' ? 'rtl' : 'ltr';
    document.documentElement.lang = lang;
    localStorage.setItem('amu-lang', lang);
  }, [lang]);
  return <LangContext.Provider value={{ lang, setLang }}>{children}</LangContext.Provider>;
}

// -------------------- Router (in-page) --------------------
const RouteContext = createContext({ route: 'home', go: () => {} });
const useRoute = () => useContext(RouteContext);
function RouteProvider({ children }) {
  const [route, setRoute] = useState(() => location.hash.replace('#','') || 'home');
  const go = useCallback((r) => { location.hash = r; setRoute(r); window.scrollTo({top:0, behavior:'instant'}); }, []);
  useEffect(() => {
    const f = () => setRoute(location.hash.replace('#','') || 'home');
    window.addEventListener('hashchange', f);
    return () => window.removeEventListener('hashchange', f);
  }, []);
  return <RouteContext.Provider value={{ route, go }}>{children}</RouteContext.Provider>;
}

// -------------------- Reveal --------------------
function Reveal({ children, delay = 0, as: As = 'div', className = '', ...rest }) {
  const ref = useRef(null);
  const [seen, setSeen] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          setTimeout(() => setSeen(true), delay);
          io.disconnect();
        }
      });
    }, { rootMargin: '0px 0px -10% 0px' });
    io.observe(el);
    return () => io.disconnect();
  }, [delay]);
  return <As ref={ref} className={`reveal ${seen ? 'in' : ''} ${className}`} {...rest}>{children}</As>;
}

// -------------------- LogoMark --------------------
function LogoMark({ size = 36, color = 'currentColor' }) {
  return (
    <svg width={size} height={size} viewBox="0 0 64 64" fill="none" style={{ color }}>
      <circle cx="32" cy="32" r="31" stroke="currentColor" strokeWidth="1.5"/>
      <path d="M18 38 C 18 28, 24 22, 32 22 C 40 22, 46 28, 46 38" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"/>
      <path d="M22 42 C 22 35, 26 31, 32 31 C 38 31, 42 35, 42 42" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" opacity="0.55"/>
      <path d="M26 46 C 26 42, 28 40, 32 40 C 36 40, 38 42, 38 46" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" opacity="0.28"/>
    </svg>
  );
}

// -------------------- Nav --------------------
function Nav() {
  const { lang, setLang } = useLang();
  const { route, go } = useRoute();
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const f = () => setScrolled(window.scrollY > 40);
    f(); window.addEventListener('scroll', f);
    return () => window.removeEventListener('scroll', f);
  }, []);

  const links = [
    { id: 'home', en: 'Home', ar: 'الرئيسية' },
    { id: 'about', en: 'About', ar: 'العيادة' },
    { id: 'services', en: 'Services', ar: 'الخدمات' },
    { id: 'booking', en: 'Book', ar: 'احجز' },
    { id: 'contact', en: 'Contact', ar: 'تواصل' },
  ];

  return (
    <nav className={`nav ${scrolled ? 'scrolled' : ''}`}>
      <div className="nav-inner">
        <a href="#home" className="nav-logo" onClick={(e)=>{e.preventDefault();go('home');}}>
          <LogoMark size={36}/>
          {lang === 'ar'
            ? <span className="wm-ar">آب مي أب</span>
            : <span className="wm-en">App Me Up</span>}
        </a>
        <div className="nav-links">
          {links.map(l => (
            <a key={l.id} href={`#${l.id}`} className={route === l.id ? 'active' : ''}
              onClick={(e)=>{e.preventDefault();go(l.id);}}>
              {lang === 'ar' ? l.ar : l.en}
            </a>
          ))}
          <div className="lang-toggle">
            <button className={lang==='ar' ? 'on' : ''} onClick={()=>setLang('ar')}>AR</button>
            <button className={lang==='en' ? 'on' : ''} onClick={()=>setLang('en')}>EN</button>
          </div>
        </div>
      </div>
    </nav>
  );
}

// -------------------- Footer --------------------
function Footer() {
  const { lang } = useLang();
  const { go } = useRoute();
  const ar = lang === 'ar';
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-inner">
          <div>
            <div style={{display:'flex',alignItems:'center',gap:14,marginBottom:18,color:'var(--sage)'}}>
              <LogoMark size={44} color="var(--sage)"/>
              {ar
                ? <div><div style={{fontFamily:'var(--font-display-ar)',fontWeight:800,fontSize:26}}>آب مي أب</div><div style={{fontSize:12,opacity:0.7,letterSpacing:'0.04em'}}>عيادة طب الأسنان</div></div>
                : <div><div style={{fontFamily:'var(--font-display-en)',fontWeight:800,fontSize:24,letterSpacing:'-0.03em'}}>App Me Up</div><div style={{fontSize:11,opacity:0.7,letterSpacing:'0.22em'}}>DENTAL CLINIC</div></div>}
            </div>
            <p style={{fontSize:14,opacity:0.75,lineHeight:1.7,maxWidth:'34ch',margin:0}}>
              {ar
                ? 'عيادة لطب الأسنان في حيّ السليمانية، الرياض. مواعيد بالحجز المسبق فقط.'
                : 'A dental clinic in Al Sulaimaniyah, Riyadh. By appointment only.'}
            </p>
          </div>
          <div>
            <h4>{ar ? 'الموقع' : 'Find us'}</h4>
            <ul>
              <li><a onClick={()=>go('about')}>{ar?'العيادة':'About'}</a></li>
              <li><a onClick={()=>go('services')}>{ar?'الخدمات':'Services'}</a></li>
              <li><a onClick={()=>go('booking')}>{ar?'احجز موعدك':'Book a visit'}</a></li>
              <li><a onClick={()=>go('contact')}>{ar?'تواصل':'Contact'}</a></li>
            </ul>
          </div>
          <div>
            <h4>{ar ? 'تواصل' : 'Contact'}</h4>
            <ul>
              <li><a href="tel:+966505354288" dir="ltr">+966 50 535 4288</a></li>
              <li><a href="mailto:info@appmeup.sa">info@appmeup.sa</a></li>
              <li><a>{ar?'السبت – الخميس · ٩ ص – ٩ م':'Sat–Thu · 9 AM – 9 PM'}</a></li>
            </ul>
          </div>
          <div>
            <h4>{ar ? 'العنوان' : 'Visit'}</h4>
            <ul>
              <li><a>{ar ? 'شارع الأمير محمد بن عبدالعزيز':'Prince Muhammad Bin Abdulaziz Rd'}</a></li>
              <li><a>{ar?'حي السليمانية، الرياض':'Al Sulaimaniyah, Riyadh'}</a></li>
              <li><a>{ar?'المملكة العربية السعودية':'Saudi Arabia'}</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-rule"></div>
        <div className="footer-bottom">
          <span>© 2026 {ar ? 'عيادة آب مي أب' : 'App Me Up Dental'}</span>
          <span>{ar ? 'مرخّصة من وزارة الصحة السعودية' : 'Licensed by the Saudi Ministry of Health'}</span>
        </div>
      </div>
    </footer>
  );
}

// -------------------- Button --------------------
function Btn({ kind = 'primary', children, onClick, ...rest }) {
  return <button className={`btn btn-${kind}`} onClick={onClick} {...rest}>{children}</button>;
}

function BtnWithArrow({ kind='primary', children, onClick }) {
  const { lang } = useLang();
  return (
    <button className={`btn btn-${kind}`} onClick={onClick}>
      <span>{children}</span>
      <span className="btn-arrow">{lang==='ar' ? '←' : '→'}</span>
    </button>
  );
}

// -------------------- Image placeholder (image-slot wrapper) --------------------
function ImgSlot({ id, label, src, style, className = '', children }) {
  return (
    <image-slot
      id={id}
      placeholder={label}
      src={src}
      shape="rounded"
      radius="18"
      style={{ display:'block', ...style }}
      class={className}
    >
      {children}
    </image-slot>
  );
}

// -------------------- Eyebrow --------------------
function Eyebrow({ children }) {
  return <div className="eyebrow"><span className="gold-rule"></span>{children}</div>;
}

// -------------------- Export to window --------------------
Object.assign(window, {
  useLang, t, LangProvider, LangContext,
  useRoute, RouteProvider,
  Reveal, LogoMark, Nav, Footer, Btn, BtnWithArrow, ImgSlot, Eyebrow,
});
