/* global React */
const { useState, useEffect, useRef, useCallback } = React;

/* ─────────────────────────────────────────────
   Icon set — minimal, consistent stroke
   ───────────────────────────────────────────── */
const Icon = ({ name, size = 22, stroke = 1.4 }) => {
  const props = {
    width: size, height: size,
    viewBox: "0 0 24 24",
    fill: "none",
    stroke: "currentColor",
    strokeWidth: stroke,
    strokeLinecap: "round",
    strokeLinejoin: "round"
  };
  const paths = {
    arrow: <><path d="M5 12h14"/><path d="M13 6l6 6-6 6"/></>,
    arrowUp: <path d="M6 9l6 6 6-6"/>,
    leaf: <><path d="M5 21c.5-9 6.5-15.5 14-16-.5 9.5-6.5 15.5-14 16z"/><path d="M5 21c4-4 7-7 9-9"/></>,
    heart: <path d="M12 20s-7-4.5-7-11a4 4 0 017-2.6A4 4 0 0119 9c0 6.5-7 11-7 11z"/>,
    bloom: <><circle cx="12" cy="12" r="2.5"/><path d="M12 4v3M12 17v3M4 12h3M17 12h3M6 6l2 2M16 16l2 2M18 6l-2 2M8 16l-2 2"/></>,
    family: <><circle cx="9" cy="8" r="3"/><circle cx="17" cy="9" r="2.2"/><path d="M3 20c0-3.5 2.7-6 6-6s6 2.5 6 6"/><path d="M14 20c.4-2.5 2.4-4 4.5-4 1.6 0 3 .8 3.5 2"/></>,
    child: <><circle cx="12" cy="7" r="3"/><path d="M6 21c0-3 2.7-5.5 6-5.5s6 2.5 6 5.5"/><path d="M10 14h4"/></>,
    moon: <path d="M20 14.5A8 8 0 119.5 4a6.5 6.5 0 0010.5 10.5z"/>,
    shield: <><path d="M12 3l8 3v5c0 5-3.5 8.5-8 10-4.5-1.5-8-5-8-10V6l8-3z"/><path d="M9 12l2 2 4-4"/></>,
    rings: <><circle cx="9" cy="14" r="5"/><circle cx="15" cy="14" r="5"/><path d="M9 5l3 3 3-3"/></>,
    scale: <><path d="M12 4v16M4 8h16"/><path d="M4 8l-2 5a3 3 0 006 0L6 8M18 8l-2 5a3 3 0 006 0l-2-5"/></>,
    podium: <><path d="M4 21h16"/><rect x="6" y="11" width="4" height="10"/><rect x="14" y="7" width="4" height="14"/><rect x="10" y="14" width="4" height="7"/></>,
    spark: <path d="M12 3l2 6 6 2-6 2-2 6-2-6-6-2 6-2z"/>,
    plus: <><path d="M12 5v14M5 12h14"/></>,
    minus: <path d="M5 12h14"/>,
    mail: <><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 7l9 6 9-6"/></>,
    phone: <path d="M5 4h4l2 5-2.5 1.5a11 11 0 005 5L15 13l5 2v4a2 2 0 01-2 2A16 16 0 013 6a2 2 0 012-2z"/>,
    map: <><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0118 0z"/><circle cx="12" cy="10" r="3"/></>,
    check: <path d="M5 12l4 4L19 7"/>,
    menu: <><path d="M4 7h16M4 17h16"/></>,
    close: <><path d="M6 6l12 12M18 6L6 18"/></>,
    quote: <path d="M7 17V11h-3a4 4 0 014-4M17 17v-6h-3a4 4 0 014-4"/>,
    clock: <><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></>,
    lock: <><rect x="5" y="11" width="14" height="9" rx="2"/><path d="M8 11V8a4 4 0 018 0v3"/></>,
    globe: <><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a14 14 0 010 18M12 3a14 14 0 000 18"/></>,
    star: <path d="M12 3l3 6 6 1-4.5 4 1 6-5.5-3-5.5 3 1-6L3 10l6-1z"/>
  };
  return <svg {...props}>{paths[name]}</svg>;
};

/* ─────────────────────────────────────────────
   Logo — custom S-monogram with leaf motif
   ───────────────────────────────────────────── */
const Logo = ({ size = 28, color, accent, showWord = true, onClick }) => {
  const c = color || 'var(--forest-deep)';
  const a = accent || 'var(--gold)';
  return (
    <span
      onClick={onClick}
      style={{ display: 'inline-flex', alignItems: 'center', gap: 12, textDecoration: 'none', cursor: onClick ? 'pointer' : 'default' }}
    >
      <svg width={size * 1.15} height={size * 1.15} viewBox="0 0 48 48" fill="none" style={{ flexShrink: 0 }}>
        {/* outer circle */}
        <circle cx="24" cy="24" r="22.5" stroke={c} strokeWidth="0.8" opacity="0.25" />
        {/* leaf/crescent stroke */}
        <path
          d="M14 33 C 14 22, 22 14, 33 14 C 33 25, 25 33, 14 33 Z"
          fill="none"
          stroke={a}
          strokeWidth="1.1"
          strokeLinecap="round"
          opacity="0.9"
        />
        {/* serif S */}
        <path
          d="M30.5 17.2 C 28.6 15.6 26.5 14.8 24.2 14.8 C 21 14.8 18.5 16.6 18.5 19.2 C 18.5 21.5 20.4 22.8 23.8 23.8 C 27.4 24.9 29.5 26.2 29.5 28.8 C 29.5 31.5 27 33.4 23.6 33.4 C 21.2 33.4 18.9 32.5 17 30.8"
          stroke={c}
          strokeWidth="1.6"
          strokeLinecap="round"
          fill="none"
        />
        {/* gold dot — center grounding */}
        <circle cx="24" cy="24" r="0.9" fill={a} />
      </svg>
      {showWord && (
        <span style={{ fontFamily: 'var(--serif)', fontSize: size * 0.78, color: c, letterSpacing: '0.005em', fontWeight: 500, lineHeight: 1 }}>
          Shifa <span style={{ color: 'var(--sage)', fontStyle: 'italic', fontWeight: 400 }}>Services</span>
        </span>
      )}
    </span>
  );
};

/* ─────────────────────────────────────────────
   Imagery — real photography (Unsplash) with gradient fallback
   ───────────────────────────────────────────── */
const IMG_SOURCES = {
  // Each photo used exactly ONCE across the entire site
  hero: 'images/ocean-hero.jpg',           // Home hero — calm ocean horizon
  meaning: 'images/maple.jpg',             // Shifa meaning — sunlit maple
  faithA: 'images/blossom-white.jpg',      // Muslim family — white plum blossoms
  faithB: 'images/wisteria.jpg',           // Muslim family — wisteria
  contact: 'images/droplet.jpg',           // Contact block — droplet
  workshopA: 'images/cherry-blossom.jpg',  // Premarital workshop
  workshopB: 'images/sunset.jpg',          // Mental health & Islam workshop
  workshopC: 'images/pier.jpg'             // Muslim youth — bridge / threshold
};

const FALLBACK_GRADIENTS = {
  linen: 'linear-gradient(135deg, #ede0c8 0%, #d6c19a 50%, #a8927a 100%)',
  foliage: 'linear-gradient(160deg, #6b7a5e 0%, #3a4a3a 60%, #2a372a 100%)',
  sand: 'linear-gradient(135deg, #f4ead4 0%, #e3d3ad 60%, #c9b687 100%)',
  sage: 'linear-gradient(150deg, #b6c2a9 0%, #8b9a82 50%, #6b7a5e 100%)',
  portrait: 'linear-gradient(160deg, #d8c8a8 0%, #b29d7a 60%, #6b5b46 100%)',
  paper: 'linear-gradient(135deg, #f7efde 0%, #ebe0c5 100%)'
};

const Imagery = ({ variant = "linen", src, aspect = "4/5", className = "", style = {}, tint = true }) => {
  const url = src || IMG_SOURCES[variant] || IMG_SOURCES.linen;
  const gradKey = FALLBACK_GRADIENTS[variant] ? variant : 'linen';
  return (
    <div
      className={`img-ph ${className}`}
      style={{
        aspectRatio: aspect,
        background: FALLBACK_GRADIENTS[gradKey],
        backgroundImage: `url(${url}), ${FALLBACK_GRADIENTS[gradKey]}`,
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        position: 'relative',
        overflow: 'hidden',
        ...style
      }}
    >
      {tint && (
        <div style={{
          position: 'absolute', inset: 0,
          background: 'linear-gradient(160deg, rgba(58,74,58,0.06), rgba(184,155,94,0.04))',
          pointerEvents: 'none'
        }} />
      )}
    </div>
  );
};

/* ─────────────────────────────────────────────
   Reveal on scroll
   ───────────────────────────────────────────── */
const Reveal = ({ children, delay = 0, as: As = 'div', className = '', style = {} }) => {
  const ref = useRef(null);
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const obs = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setTimeout(() => setVisible(true), delay);
          obs.disconnect();
        }
      },
      { threshold: 0.12, rootMargin: '0px 0px -60px 0px' }
    );
    obs.observe(el);
    return () => obs.disconnect();
  }, [delay]);
  return (
    <As ref={ref} className={`reveal ${visible ? 'in' : ''} ${className}`} style={style}>
      {children}
    </As>
  );
};

/* ─────────────────────────────────────────────
   Header / nav
   ───────────────────────────────────────────── */
const Header = ({ currentPage, onNavigate }) => {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  const links = [
    ['home', 'Home'],
    ['about', 'About'],
    ['services', 'Services'],
    ['team', 'Team'],
    ['workshops', 'Workshops'],
    ['faq', 'FAQ'],
    ['contact', 'Contact']
  ];
  const go = (p) => {
    onNavigate(p);
    setOpen(false);
  };
  return (
    <header className={`header ${scrolled ? 'scrolled' : ''}`}>
      <div className="header-inner">
        <div className="brand" onClick={() => go('home')} style={{ cursor: 'pointer' }}>
          <span style={{ fontFamily: 'var(--serif)', fontSize: 24, color: 'var(--forest-deep)', letterSpacing: '0.005em', fontWeight: 500, lineHeight: 1 }}>
            Shifa <span style={{ color: 'var(--sage)', fontStyle: 'italic', fontWeight: 400 }}>Services</span>
          </span>
        </div>
        <nav className={`nav ${open ? 'open' : ''}`}>
          {links.map(([k, l]) => (
            <a
              key={k}
              className={currentPage === k ? 'active' : ''}
              onClick={() => go(k)}
            >
              {l}
            </a>
          ))}
        </nav>
        <button className="btn btn-primary nav-cta" onClick={() => go('contact')}>
          Book Consultation
          <Icon name="arrow" size={16} />
        </button>
        <button
          className="mobile-toggle"
          aria-label="Toggle menu"
          onClick={() => setOpen(o => !o)}
        >
          <Icon name={open ? 'close' : 'menu'} size={20} />
        </button>
      </div>
    </header>
  );
};

/* ─────────────────────────────────────────────
   Footer
   ───────────────────────────────────────────── */
const Footer = ({ onNavigate }) => {
  return (
    <footer className="footer">
      <div className="container">
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1fr', gap: 64, alignItems: 'start' }} className="footer-grid">
          <div>
            <div style={{ marginBottom: 18 }}>
              <Logo size={28} color="var(--cream)" accent="var(--gold-soft)" />
            </div>
            <p style={{ color: 'rgba(251,247,239,0.65)', fontSize: 14, lineHeight: 1.7, maxWidth: 360 }}>
              Counselling, family support, consultation, and spiritually aware care for individuals, couples, families, and communities.
            </p>
            <div style={{ marginTop: 28, display: 'flex', gap: 24, alignItems: 'center' }}>
              <span style={{ color: 'var(--gold-soft)', fontSize: 12, letterSpacing: '0.18em', textTransform: 'uppercase' }}>
                <Icon name="leaf" size={14} /> Healing, restored
              </span>
            </div>
          </div>
          <div>
            <h4>Explore</h4>
            <a onClick={() => onNavigate('about')}>About Shifa</a>
            <a onClick={() => onNavigate('services')}>Services</a>
            <a onClick={() => onNavigate('team')}>Team</a>
            <a onClick={() => onNavigate('workshops')}>Workshops</a>
            <a onClick={() => onNavigate('faq')}>FAQ</a>
          </div>
          <div>
            <h4>Services</h4>
            <a onClick={() => onNavigate('services')}>Counselling</a>
            <a onClick={() => onNavigate('services')}>Couples & Marriage</a>
            <a onClick={() => onNavigate('services')}>Family Support</a>
            <a onClick={() => onNavigate('services')}>Child & Youth</a>
            <a onClick={() => onNavigate('services')}>Premarital</a>
          </div>
          <div>
            <h4>Connect</h4>
            <a href="mailto:info@shifaservices.com">info@shifaservices.com</a>
            <a href="tel:4166484555">(416) 648-4555</a>
            <a onClick={() => onNavigate('contact')}>Book a Consultation</a>
          </div>
        </div>

        <hr style={{ border: 0, height: 1, background: 'rgba(251,247,239,0.12)', margin: '64px 0 28px' }} />

        <div style={{ display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 16, fontSize: 12, color: 'rgba(251,247,239,0.5)', letterSpacing: '0.04em' }}>
          <div>© {new Date().getFullYear()} Shifa Services. All rights reserved.</div>
          <div style={{ display: 'flex', gap: 28 }}>
            <a style={{ display: 'inline', padding: 0, fontSize: 12 }} href="#">Privacy Policy</a>
            <a style={{ display: 'inline', padding: 0, fontSize: 12 }} href="#">Accessibility Statement</a>
          </div>
        </div>
      </div>

      <style>{`
        @media (max-width: 900px) {
          .footer-grid { grid-template-columns: 1fr 1fr !important; gap: 40px !important; }
        }
        @media (max-width: 560px) {
          .footer-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </footer>
  );
};

/* ─────────────────────────────────────────────
   Accordion
   ───────────────────────────────────────────── */
const Accordion = ({ items, defaultOpen = -1 }) => {
  const [open, setOpen] = useState(defaultOpen);
  return (
    <div>
      {items.map((it, i) => (
        <div
          key={i}
          className="acc-item"
          data-open={open === i}
          onClick={() => setOpen(open === i ? -1 : i)}
        >
          <div className="acc-q">
            <span>{it.q}</span>
            <span className="acc-toggle">
              <Icon name={open === i ? 'minus' : 'plus'} size={16} stroke={1.6} />
            </span>
          </div>
          <div className="acc-a">{it.a}</div>
        </div>
      ))}
    </div>
  );
};

/* ─────────────────────────────────────────────
   Section header
   ───────────────────────────────────────────── */
const SectionHeader = ({ eyebrow, title, lede, align = 'left', style = {} }) => (
  <Reveal>
    <div style={{ textAlign: align, maxWidth: align === 'center' ? 760 : 'none', margin: align === 'center' ? '0 auto' : 0, ...style }}>
      {eyebrow && (
        <div className="eyebrow" style={{ marginBottom: 22 }}>
          <span className="dot" />{eyebrow}
        </div>
      )}
      <h2 style={{ marginBottom: lede ? 24 : 0 }}>{title}</h2>
      {lede && <p className="lede" style={{ maxWidth: 640, margin: align === 'center' ? '0 auto' : 0 }}>{lede}</p>}
    </div>
  </Reveal>
);

/* expose to other scripts */
Object.assign(window, { Icon, Imagery, Reveal, Header, Footer, Accordion, SectionHeader, Logo });
