// Shared components + hooks for Sohail Merchant portfolio
// Loaded on every page. Exposes globals via window.

const DS = () => window.KrystalDesignSystem_a15719;

// ---- Site data (edit here) ----
const SITE = {
  name: 'Sohail Merchant',
  role: 'Graphic Designer & Web Developer',
  city: 'Vadodara, India',
  email: 'hello@sohailmerchant.com',
  phone: '+91 98765 43210',
  social: {
    instagram: 'https://instagram.com/',
    linkedin: 'https://linkedin.com/in/',
    facebook: 'https://facebook.com/',
  },
};
window.SITE = SITE;

// ---- Dark mode (persisted) ----
function useDarkMode() {
  const [dark, setDark] = React.useState(() => {
    try { return localStorage.getItem('sm-theme') === 'dark'; } catch (e) { return false; }
  });
  React.useEffect(() => {
    document.documentElement.setAttribute('data-theme', dark ? 'dark' : 'light');
    try { localStorage.setItem('sm-theme', dark ? 'dark' : 'light'); } catch (e) {}
  }, [dark]);
  return [dark, () => setDark(d => !d)];
}
window.useDarkMode = useDarkMode;

// ---- Scroll reveal hook ----
function useReveal() {
  React.useEffect(() => {
    const els = document.querySelectorAll('[data-reveal]');
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
      els.forEach(el => el.classList.add('is-in'));
      return;
    }
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) { e.target.classList.add('is-in'); io.unobserve(e.target); } });
    }, { threshold: 0.12 });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  });
}
window.useReveal = useReveal;

// ---- Animated counter ----
function Counter({ to, suffix = '', duration = 1600 }) {
  const ref = React.useRef(null);
  const [val, setVal] = React.useState(0);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    let raf, started = false;
    const run = () => {
      const t0 = performance.now();
      const tick = (now) => {
        const p = Math.min(1, (now - t0) / duration);
        const eased = 1 - Math.pow(1 - p, 3);
        setVal(Math.round(to * eased));
        if (p < 1) raf = requestAnimationFrame(tick);
      };
      raf = requestAnimationFrame(tick);
    };
    const io = new IntersectionObserver((es) => {
      es.forEach(e => { if (e.isIntersecting && !started) { started = true; run(); io.unobserve(el); } });
    }, { threshold: 0.5 });
    io.observe(el);
    return () => { io.disconnect(); cancelAnimationFrame(raf); };
  }, [to, duration]);
  return <span ref={ref}>{val.toLocaleString()}{suffix}</span>;
}
window.Counter = Counter;

// ---- Section title block ----
function SectionHead({ eyebrow, title, sub, center }) {
  return (
    <div data-reveal className="reveal" style={{ maxWidth: 720, margin: center ? '0 auto' : 0, textAlign: center ? 'center' : 'left', marginBottom: 48 }}>
      {eyebrow && <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontFamily: 'var(--font-heading)', fontWeight: 700, fontSize: 13, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--color-secondary)', marginBottom: 16 }}>
        <span style={{ width: 24, height: 2, background: 'var(--color-accent)', display: 'inline-block' }}></span>{eyebrow}
      </div>}
      <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 'clamp(30px,4.5vw,44px)', lineHeight: 1.1, letterSpacing: '-0.02em', color: 'var(--text-primary)', margin: 0 }}>{title}</h2>
      {sub && <p style={{ fontFamily: 'var(--font-body)', fontSize: 18, lineHeight: 1.7, color: 'var(--text-secondary)', margin: '16px auto 0', maxWidth: 620 }}>{sub}</p>}
    </div>
  );
}
window.SectionHead = SectionHead;

// ---- Top nav ----
function Nav({ active }) {
  const { Button, Switch } = DS();
  const [dark, toggleDark] = useDarkMode();
  const [open, setOpen] = React.useState(false);
  const links = [
    { label: 'Home', href: 'index.html', key: 'home' },
    { label: 'Work', href: 'Work.html', key: 'work' },
    { label: 'About', href: 'About.html', key: 'about' },
    { label: 'Blog', href: 'Blog.html', key: 'blog' },
    { label: 'Contact', href: 'Contact.html', key: 'contact' },
  ];
  return (
    <header style={{
      position: 'sticky', top: 16, zIndex: 60, margin: '16px auto 0', maxWidth: 1200, width: 'calc(100% - 32px)',
      display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 20,
      padding: '10px 12px 10px 20px', background: 'var(--glass-bg)', WebkitBackdropFilter: 'var(--glass-blur)', backdropFilter: 'var(--glass-blur)',
      border: '1px solid var(--glass-border)', borderRadius: 'var(--radius-round)', boxShadow: 'var(--shadow-md)',
    }}>
      <a href="index.html" style={{ display: 'flex', alignItems: 'center', gap: 11, textDecoration: 'none' }}>
        <div style={{ width: 36, height: 36, borderRadius: 11, background: 'linear-gradient(135deg,#1D5C42,#617A55)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#F9E900', fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 19 }}>SM</div>
        <span style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 19, letterSpacing: '-0.02em', color: 'var(--text-primary)' }}>Sohail<span style={{ color: 'var(--color-secondary)' }}>.</span></span>
      </a>
      <nav className="site-nav" style={{ display: 'flex', gap: 26 }}>
        {links.map(l => (
          <a key={l.key} href={l.href} style={{ fontSize: 15, fontWeight: active === l.key ? 700 : 500, color: active === l.key ? 'var(--text-primary)' : 'var(--text-secondary)', textDecoration: 'none', position: 'relative' }}>{l.label}
            {active === l.key && <span style={{ position: 'absolute', left: 0, right: 0, bottom: -6, height: 2, background: 'var(--color-primary)', borderRadius: 2 }}></span>}
          </a>
        ))}
      </nav>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
        <Switch aria-label="Dark mode" checked={dark} onChange={toggleDark} />
        <div className="nav-cta"><Button size="sm" onClick={() => location.href = 'Contact.html'}>Let's talk</Button></div>
        <button className="nav-burger" aria-label="Menu" onClick={() => setOpen(o => !o)} style={{ display: 'none', background: 'none', border: 'none', cursor: 'pointer', padding: 8 }}>
          <i data-lucide={open ? 'x' : 'menu'} style={{ width: 22, height: 22, color: 'var(--text-primary)' }}></i>
        </button>
      </div>
      {open && <div className="mobile-menu" style={{ position: 'absolute', top: 68, left: 0, right: 0, background: 'var(--surface-card)', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-lg)', padding: 16, display: 'flex', flexDirection: 'column', gap: 4, boxShadow: 'var(--shadow-lg)' }}>
        {links.map(l => <a key={l.key} href={l.href} style={{ padding: '12px 14px', borderRadius: 12, fontSize: 16, fontWeight: 600, color: active === l.key ? 'var(--color-primary)' : 'var(--text-primary)', textDecoration: 'none' }}>{l.label}</a>)}
      </div>}
    </header>
  );
}
window.Nav = Nav;

// ---- Footer ----
function Footer() {
  const socials = [
    { icon: 'instagram', href: SITE.social.instagram, label: 'Instagram' },
    { icon: 'linkedin', href: SITE.social.linkedin, label: 'LinkedIn' },
    { icon: 'facebook', href: SITE.social.facebook, label: 'Facebook' },
  ];
  const cols = [
    { h: 'Explore', links: [['Home', 'index.html'], ['Work', 'Work.html'], ['About', 'About.html'], ['Blog', 'Blog.html']] },
    { h: 'Services', links: [['Branding & logos', 'Work.html'], ['Web development', 'Work.html'], ['UI/UX design', 'Work.html'], ['Digital marketing', 'Work.html']] },
  ];
  return (
    <footer style={{ background: 'var(--surface-muted)', borderTop: '1px solid var(--border-default)', marginTop: 96 }}>
      <div style={{ maxWidth: 1200, margin: '0 auto', padding: '72px 24px 40px', display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr', gap: 40 }} className="footer-grid">
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 11, marginBottom: 18 }}>
            <div style={{ width: 36, height: 36, borderRadius: 11, background: 'linear-gradient(135deg,#1D5C42,#617A55)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#F9E900', fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 19 }}>SM</div>
            <span style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 20, color: 'var(--text-primary)' }}>Sohail Merchant</span>
          </div>
          <p style={{ fontSize: 15, lineHeight: 1.7, color: 'var(--text-secondary)', maxWidth: 300, margin: 0 }}>Graphic designer & web developer crafting bold brands and fast, beautiful websites from {SITE.city}.</p>
          <div style={{ display: 'flex', gap: 10, marginTop: 22 }}>
            {socials.map(s => (
              <a key={s.icon} href={s.href} aria-label={s.label} target="_blank" rel="noopener" style={{ width: 42, height: 42, borderRadius: 12, border: '1px solid var(--border-default)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--text-primary)', background: 'var(--surface-card)' }}>
                <i data-lucide={s.icon} style={{ width: 18, height: 18 }}></i>
              </a>
            ))}
          </div>
        </div>
        {cols.map(c => (
          <div key={c.h}>
            <div style={{ fontFamily: 'var(--font-heading)', fontWeight: 700, fontSize: 14, letterSpacing: '0.04em', color: 'var(--text-primary)', marginBottom: 16 }}>{c.h}</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              {c.links.map(([t, h]) => <a key={t} href={h} style={{ fontSize: 15, color: 'var(--text-secondary)', textDecoration: 'none' }}>{t}</a>)}
            </div>
          </div>
        ))}
      </div>
      <div style={{ maxWidth: 1200, margin: '0 auto', padding: '20px 24px 40px', borderTop: '1px solid var(--border-default)', display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12 }}>
        <span style={{ fontSize: 13, color: 'var(--text-secondary)' }}>© 2026 {SITE.name}. All rights reserved.</span>
        <span style={{ fontSize: 13, color: 'var(--text-secondary)' }}>Designed & built in {SITE.city}</span>
      </div>
    </footer>
  );
}
window.Footer = Footer;

// refresh lucide icons after render
window.refreshIcons = () => { if (window.lucide) window.lucide.createIcons(); };
