/* ============================================
   H-Arch — Shared UI primitives
   Nav · Footer · Buttons · Drawer · Forms · Toast · Icons
   ============================================ */
const { useState, useEffect, useRef, useCallback, useMemo } = React;

/* ---------- Icons (inline SVG only — no third-party) ---------- */
const Icon = {
  arrow: (p) => (
    <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4">
      <path d="M5 12h14M13 5l7 7-7 7" />
    </svg>
  ),
  close: (p) => (
    <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6">
      <path d="M6 6l12 12M18 6L6 18" />
    </svg>
  ),
  download: (p) => (
    <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4">
      <path d="M12 4v12M6 12l6 6 6-6M4 20h16" />
    </svg>
  ),
  whatsapp: (p) => (
    <svg {...p} viewBox="0 0 24 24" fill="currentColor">
      <path d="M17.5 14.4c-.3-.1-1.7-.8-1.9-.9-.3-.1-.4-.1-.6.1-.2.3-.7.9-.8 1-.2.2-.3.2-.5.1s-1.1-.4-2.1-1.3c-.8-.7-1.3-1.6-1.5-1.8-.2-.3 0-.4.1-.6l.4-.5c.1-.2.2-.3.2-.5.1-.2 0-.3 0-.5L9.9 7c-.2-.5-.4-.4-.6-.4h-.5c-.2 0-.5.1-.7.3-.3.3-1 1-1 2.4s1 2.8 1.2 3c.1.2 2 3 4.8 4.2 1.7.7 2.3.8 3.1.7.5-.1 1.7-.7 1.9-1.4.2-.7.2-1.3.2-1.4-.1-.1-.3-.2-.5-.3zM12 2C6.5 2 2 6.5 2 12c0 1.8.5 3.5 1.4 5L2 22l5.2-1.4c1.4.8 3.1 1.2 4.8 1.2 5.5 0 10-4.5 10-10S17.5 2 12 2zm0 18c-1.6 0-3.1-.4-4.4-1.2l-.3-.2-3.1.8.8-3-.2-.3C3.9 14.8 3.4 13.4 3.4 12c0-4.7 3.9-8.6 8.6-8.6s8.6 3.9 8.6 8.6-3.9 8.6-8.6 8.6z"/>
    </svg>
  ),
  ig: (p) => (
    <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
      <rect x="3" y="3" width="18" height="18" rx="5"/>
      <circle cx="12" cy="12" r="3.5"/>
      <circle cx="17" cy="7" r="0.8" fill="currentColor"/>
    </svg>
  ),
  li: (p) => (
    <svg {...p} viewBox="0 0 24 24" fill="currentColor">
      <path d="M4 4h4v16H4zM6 2.5a2 2 0 1 0 0 4 2 2 0 0 0 0-4zM10 8h4v2.1c.6-1 2-2.4 4.3-2.4 3 0 4.7 2 4.7 5.6V20h-4v-5.7c0-1.6-.6-2.7-2.2-2.7-1.6 0-2.5 1-2.5 2.7V20h-4V8z"/>
    </svg>
  ),
  yt: (p) => (
    <svg {...p} viewBox="0 0 24 24" fill="currentColor">
      <path d="M22 12c0-2.4-.3-4-.3-4-.3-1-1-1.7-2-2-1.8-.5-7.7-.5-7.7-.5s-5.9 0-7.7.5c-1 .3-1.7 1-2 2 0 0-.3 1.6-.3 4s.3 4 .3 4c.3 1 1 1.7 2 2 1.8.5 7.7.5 7.7.5s5.9 0 7.7-.5c1-.3 1.7-1 2-2 0 0 .3-1.6.3-4zM10 15V9l5 3-5 3z"/>
    </svg>
  ),
  pin: (p) => (
    <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4">
      <path d="M12 21s-7-7.5-7-12a7 7 0 1 1 14 0c0 4.5-7 12-7 12z"/>
      <circle cx="12" cy="9" r="2.5"/>
    </svg>
  ),
  search: (p) => (
    <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4">
      <circle cx="11" cy="11" r="7"/>
      <path d="M21 21l-4-4"/>
    </svg>
  ),
  check: (p) => (
    <svg {...p} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
      <path d="M5 12l5 5 9-11"/>
    </svg>
  ),
};

/* ---------- Brand mark ---------- */
function BrandMark({ size = 40 }) {
  return (
    <div className="nav__mark" style={{ width: size, height: size }}>
      <svg viewBox="0 0 32 32" fill="none">
        <rect x="3" y="3" width="26" height="26" stroke="white" strokeWidth="2.4" />
        <rect x="9" y="8" width="3" height="16" fill="white"/>
        <rect x="20" y="8" width="3" height="16" fill="white"/>
        <rect x="13.5" y="14" width="5" height="4" fill="white"/>
      </svg>
    </div>
  );
}

/* ---------- Buttons ---------- */
function Button({ variant = 'primary', size, onLight, children, className = '', ...rest }) {
  const cls = [
    'btn',
    `btn--${variant}`,
    size === 'lg' && 'btn--lg',
    size === 'sm' && 'btn--small',
    onLight && 'on-light',
    className,
  ].filter(Boolean).join(' ');
  return <button className={cls} {...rest}>{children}</button>;
}

/* ---------- Nav ---------- */
function Nav({ route, setRoute, theme = 'light' }) {
  const [open, setOpen] = useState(false);
  const links = [
    ['home',         'Index'],
    ['finishes',     'Finishes'],
    ['projects',     'Projects'],
    ['capabilities', 'Capabilities'],
    ['showroom',     'The d3 showroom'],
    ['contact',      'Contact'],
  ];
  return (
    <nav className={`nav ${theme === 'dark' ? 'on-dark' : ''}`}>
      <a className="nav__brand" onClick={(e) => { e.preventDefault(); setRoute('home'); }} href="#home">
        <BrandMark />
        <div className="nav__wordmark">
          <span className="nav__wordmark-top">H-Arch</span>
          <span className="nav__wordmark-bot">By Hidayath · d3</span>
        </div>
      </a>
      <div className={`nav__menu ${open ? 'is-open' : ''}`}>
        {links.map(([key, label]) => (
          <a key={key} href={`#${key}`}
             onClick={(e) => { e.preventDefault(); setRoute(key); setOpen(false); }}
             className={`nav__link ${route === key ? 'is-active' : ''}`}>
            {label}
          </a>
        ))}
      </div>
      <Button variant="primary" size="sm" className="nav__cta"
              onClick={() => setRoute('contact')}>
        Book a consultation
      </Button>
      <button className="nav__hamburger" onClick={() => setOpen(!open)} aria-label="Menu">
        <span/>
      </button>
    </nav>
  );
}

/* ---------- Heritage ticker ---------- */
function Ticker() {
  const items = [
    'Backed by Hidayath Group',
    'Metalwork since 1976',
    "UAE's largest integrated stainless-steel service centre",
    '20+ countries · five continents',
    'In-house fabrication & finishing',
    'Specifier atelier · Dubai Design District',
  ];
  const doubled = [...items, ...items];
  return (
    <div className="ticker">
      <div className="ticker__track">
        {doubled.map((item, i) => (
          <span key={i} className="ticker__item">
            {item}
            <span className="ticker__dot" />
          </span>
        ))}
      </div>
    </div>
  );
}

/* ---------- Toast ---------- */
function Toast({ msg, onDone }) {
  useEffect(() => {
    if (!msg) return;
    const t = setTimeout(onDone, 2800);
    return () => clearTimeout(t);
  }, [msg, onDone]);
  if (!msg) return null;
  return (
    <div className="toast" role="status">
      <span className="toast__dot" />
      {msg}
    </div>
  );
}

/* ---------- WhatsApp FAB ---------- */
function WhatsAppFab() {
  const href = 'https://wa.me/971586332122?text=' +
    encodeURIComponent("Hello H-Arch — I'd like to enquire about a project at d3.");
  return (
    <a className="fab" href={href} target="_blank" rel="noreferrer" aria-label="WhatsApp">
      <Icon.whatsapp />
    </a>
  );
}

/* ---------- Footer ---------- */
function Footer({ setRoute, onSample }) {
  return (
    <footer className="footer">
      <div className="footer__inner">
        <div>
          <div className="footer__lede">
            A specifier's atelier for architectural metal — at Dubai Design District.
          </div>
          <a className="footer__group-link" href="https://hidayath.com" target="_blank" rel="noreferrer">
            Part of Hidayath Group · since 1976 <Icon.arrow className="arrow" style={{ width: 14, height: 14 }} />
          </a>
        </div>

        <div className="footer__col">
          <div className="footer__col-head">Explore</div>
          <ul>
            <li><a href="#finishes" onClick={(e) => { e.preventDefault(); setRoute('finishes'); }}>Finishes library</a></li>
            <li><a href="#projects" onClick={(e) => { e.preventDefault(); setRoute('projects'); }}>Projects</a></li>
            <li><a href="#capabilities" onClick={(e) => { e.preventDefault(); setRoute('capabilities'); }}>Capabilities</a></li>
            <li><a href="#showroom" onClick={(e) => { e.preventDefault(); setRoute('showroom'); }}>The d3 showroom</a></li>
          </ul>
        </div>

        <div className="footer__col">
          <div className="footer__col-head">For specifiers</div>
          <ul>
            <li><a onClick={onSample} href="#sample">Request samples</a></li>
            <li><a href="https://hidayath.com/media/hidayath-architectural-catalogue-new.pdf" target="_blank" rel="noreferrer">Architectural catalogue (PDF)</a></li>
            <li><a href="#contact" onClick={(e) => { e.preventDefault(); setRoute('contact'); }}>Book a consultation</a></li>
            <li><a href="https://wa.me/971586332122" target="_blank" rel="noreferrer">WhatsApp the group</a></li>
          </ul>
        </div>

        <div className="footer__col">
          <div className="footer__col-head">d3 Studio</div>
          <p>
            Office 103B, Building 5<br/>
            Dubai Design District (d3)<br/>
            Za'abeel 2, Dubai · UAE
          </p>
          <p style={{ marginTop: 12 }}>
            <a href="tel:+97148857700">+971 4 8857 700</a><br/>
            <a href="mailto:info@h-arch.com">info@h-arch.com</a>
          </p>
        </div>
      </div>

      <div className="footer__legal">
        <span>© 1976 – 2026 Hidayath Group. H-Arch is a division of Hidayath Group.</span>
        <div className="footer__socials" aria-label="Social">
          <a href="https://instagram.com/hidayathgroup" target="_blank" rel="noreferrer" aria-label="Instagram"><Icon.ig /></a>
          <a href="https://linkedin.com/company/hidayath-group" target="_blank" rel="noreferrer" aria-label="LinkedIn"><Icon.li /></a>
          <a href="https://youtube.com/channel/UCgWXvEoJF-1ExYU1P5R2d_Q" target="_blank" rel="noreferrer" aria-label="YouTube"><Icon.yt /></a>
          <a href="https://pinterest.com/hidayathgroup" target="_blank" rel="noreferrer" aria-label="Pinterest"><Icon.pin /></a>
        </div>
      </div>
    </footer>
  );
}

/* ---------- Sample request drawer ---------- */
function FinishDrawer({ finish, onClose, onSubmit }) {
  const [form, setForm] = useState({ name: '', firm: '', project: '', message: '' });
  const [sent, setSent] = useState(false);
  const handle = (k) => (e) => setForm({ ...form, [k]: e.target.value });

  useEffect(() => {
    if (!finish) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [finish, onClose]);

  // Reset local form when finish changes
  useEffect(() => {
    setForm({ name: '', firm: '', project: '', message: '' });
    setSent(false);
  }, [finish && finish.slug]);

  if (!finish) return null;

  const submit = (e) => {
    e.preventDefault();
    if (!form.name || !form.firm) return;
    setSent(true);
    onSubmit(`Sample request logged for ${finish.name} — we'll be in touch within one business day.`);
  };

  return (
    <>
      <div className="drawer-backdrop" onClick={onClose} />
      <aside className="drawer" role="dialog">
        <button className="drawer__close" onClick={onClose} aria-label="Close">
          <Icon.close style={{ width: 18, height: 18 }} />
        </button>

        <div className="drawer__hero">
          <img src={finish.img} alt={finish.name} />
          <div className="drawer__hero-meta">
            <div className="drawer__family">{finish.familyLabel} · {finish.code}</div>
            <h1 className="drawer__name">{finish.name}</h1>
          </div>
        </div>

        <div className="drawer__body">
          <div>
            <div className="eyebrow" style={{ marginBottom: 14 }}>The finish</div>
            <p className="drawer__desc">{finish.desc}</p>

            <div style={{ marginTop: 40 }}>
              <div className="eyebrow" style={{ marginBottom: 14 }}>Specification</div>
              <div className="drawer__spec-row">
                <span className="drawer__spec-label">Applications</span>
                <span className="drawer__spec-value">{finish.apps.join(' · ')}</span>
              </div>
              <div className="drawer__spec-row">
                <span className="drawer__spec-label">Base materials</span>
                <span className="drawer__spec-value">{finish.base.join(' · ')}</span>
              </div>
              <div className="drawer__spec-row">
                <span className="drawer__spec-label">Sheet & gauge</span>
                <span className="drawer__spec-value">{finish.sheet.join(' · ')}</span>
              </div>
              <div className="drawer__spec-row">
                <span className="drawer__spec-label">Finish code</span>
                <span className="drawer__spec-value text-mono">{finish.code}</span>
              </div>
              <div className="drawer__spec-row" style={{ borderBottom: 0 }}>
                <span className="drawer__spec-label">Lead time</span>
                <span className="drawer__spec-value muted">Per project — request a quote</span>
              </div>
            </div>
          </div>

          <div className="drawer__form-card">
            {sent ? (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <Icon.check style={{ width: 22, height: 22, color: '#B68CD0' }} />
                  <h3 className="drawer__form-title" style={{ margin: 0 }}>Sample on the way</h3>
                </div>
                <p className="drawer__form-blurb">
                  We've logged your request for <strong>{finish.name}</strong>. Mr. Syed Furqan or a member of the d3 team will be in touch within one business day with samples and the spec sheet.
                </p>
                <Button variant="ghost" onClick={onClose}>Close</Button>
              </div>
            ) : (
              <>
                <h3 className="drawer__form-title">Request a sample</h3>
                <p className="drawer__form-blurb">
                  We send physical swatches to architects, designers and fit-out contractors in the UAE & GCC.
                </p>
                <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
                  <div className="field">
                    <label>Your name</label>
                    <input value={form.name} onChange={handle('name')} required placeholder="Jane Doe" />
                  </div>
                  <div className="field">
                    <label>Firm / practice</label>
                    <input value={form.firm} onChange={handle('firm')} required placeholder="Studio name" />
                  </div>
                  <div className="field">
                    <label>Project (optional)</label>
                    <input value={form.project} onChange={handle('project')} placeholder="Hospitality lobby, Downtown Dubai" />
                  </div>
                  <div className="field">
                    <label>Anything specific?</label>
                    <textarea value={form.message} onChange={handle('message')} rows="2" placeholder={`I'd like the ${finish.name} swatch plus three tones in the family.`} />
                  </div>
                  <Button variant="primary" type="submit" style={{ marginTop: 6 }}>
                    Send request <Icon.arrow className="arrow" style={{ width: 14, height: 14 }} />
                  </Button>
                  <Button variant="ghost" type="button"
                          onClick={() => window.open('https://hidayath.com/media/hidayath-architectural-catalogue-new.pdf', '_blank')}>
                    <Icon.download style={{ width: 14, height: 14 }} />
                    Download spec sheet
                  </Button>
                </form>
              </>
            )}
          </div>
        </div>
      </aside>
    </>
  );
}

/* ---------- Scroll-reveal helper ---------- */
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll('.reveal:not(.is-visible)');
    if (!('IntersectionObserver' in window)) {
      els.forEach((el) => el.classList.add('is-visible'));
      return;
    }
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          e.target.classList.add('is-visible');
          io.unobserve(e.target);
        }
      });
    }, { rootMargin: '0px 0px -8% 0px', threshold: 0.05 });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  });
}

Object.assign(window, {
  Icon, BrandMark, Button, Nav, Ticker, Toast, WhatsAppFab, Footer, FinishDrawer, useReveal,
});
