// Layout.jsx — Header, Footer, QuoteBar, ContactModal

function Header({ onContactClick }) {
  const { path, navigate } = useRouter();
  const [scrolled, setScrolled] = React.useState(false);
  const [mobileOpen, setMobileOpen] = React.useState(false);

  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  React.useEffect(() => { setMobileOpen(false); }, [path]);

  const links = [
    { to: '/', label: 'Home' },
    { to: '/services', label: 'Services' },
    { to: '/about', label: 'About' },
    { to: '/blog', label: 'Blog' },
    { to: '/contact', label: 'Contact' },
  ];

  const isActive = (to) => to === '/' ? path === '/' : path === to || path.startsWith(to + '/');

  return (
    <header style={{
      position: 'sticky', top: 0, zIndex: 50,
      background: scrolled ? 'rgba(255,255,255,0.86)' : 'rgba(255,255,255,0.6)',
      backdropFilter: 'saturate(180%) blur(12px)',
      WebkitBackdropFilter: 'saturate(180%) blur(12px)',
      borderBottom: scrolled ? '1px solid var(--border-subtle)' : '1px solid transparent',
      transition: 'all 240ms',
    }}>
      <div className="container" style={{
        padding: '14px var(--container-pad)',
        display: 'flex', alignItems: 'center', gap: 32,
      }}>
        <Link to="/" style={{ display: 'flex', alignItems: 'center', gap: 12, textDecoration: 'none' }}>
          <img src="assets/logo-mark-cyan.png" alt="" style={{ height: 42 }} />
          <span style={{ fontWeight: 700, fontSize: 26, color: 'var(--cw-navy-700)', letterSpacing: '-0.01em' }}>CloudWise</span>
        </Link>
        <nav className="desktop-only" style={{ display: 'flex', gap: 32, marginLeft: 20 }}>
          {links.map(l => (
            <Link key={l.to} to={l.to} style={{
              fontSize: 17, fontWeight: 500,
              color: isActive(l.to) ? 'var(--cw-navy-700)' : 'var(--fg-3)',
              textDecoration: 'none',
              paddingBottom: 4,
              borderBottom: isActive(l.to) ? '2px solid var(--cw-sky-500)' : '2px solid transparent',
              transition: 'color 150ms, border-color 150ms',
            }}>
              {l.label}
            </Link>
          ))}
        </nav>
        <div style={{ marginLeft: 'auto' }} className="desktop-only">
          <button className="btn btn-primary sm" onClick={onContactClick}>
            Get a quote <Icon.arrow />
          </button>
        </div>
        <button
          className="mobile-only"
          onClick={() => setMobileOpen(o => !o)}
          aria-label="Menu"
          style={{
            marginLeft: 'auto', background: 'transparent', border: 'none', cursor: 'pointer',
            color: 'var(--cw-navy-700)', padding: 8,
          }}>
          {mobileOpen ? <Icon.close /> : <Icon.menu />}
        </button>
      </div>
      {mobileOpen && (
        <div className="mobile-only" style={{
          flexDirection: 'column',
          padding: '8px var(--container-pad) 24px',
          background: '#fff',
          borderTop: '1px solid var(--border-subtle)',
        }}>
          {links.map(l => (
            <Link key={l.to} to={l.to} style={{
              padding: '14px 0',
              borderBottom: '1px solid var(--border-subtle)',
              fontSize: 16, fontWeight: 500,
              color: isActive(l.to) ? 'var(--cw-sky-600)' : 'var(--fg-1)',
              textDecoration: 'none',
            }}>{l.label}</Link>
          ))}
          <button className="btn btn-primary" style={{ marginTop: 18 }} onClick={() => { setMobileOpen(false); onContactClick(); }}>
            Get a quote <Icon.arrow />
          </button>
        </div>
      )}
    </header>
  );
}

function Footer() {
  const cols = [
    { title: 'Services', links: SERVICES.map(s => ({ label: s.title, to: '/services/' + s.slug })) },
    { title: 'Company', links: [
      { label: 'About us', to: '/about' },
      { label: 'Blog', to: '/blog' },
      { label: 'Contact', to: '/contact' },
    ]},
  ];
  return (
    <footer style={{ background: 'var(--cw-navy-900)', color: 'var(--cw-navy-100)', padding: '88px 0 32px', position: 'relative', overflow: 'hidden' }}>
      <div className="grid-bg" style={{ position: 'absolute', inset: 0, opacity: 0.5, pointerEvents: 'none' }}></div>
      <div className="container" style={{ position: 'relative' }}>
        <div style={{
          display: 'grid', gridTemplateColumns: '1.6fr 1fr 1fr 1.2fr', gap: 48, marginBottom: 56,
        }} className="footer-grid">
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 20 }}>
              <img src="assets/logo-mark-cyan.png" alt="" style={{ height: 32 }} />
              <span style={{ fontWeight: 700, fontSize: 22, color: '#fff', letterSpacing: '-0.01em' }}>CloudWise</span>
            </div>
            <p style={{ color: 'var(--cw-navy-200)', fontSize: 15, lineHeight: 1.65, maxWidth: 340, marginBottom: 24 }}>
              Smart, secure and scalable IT for Gibraltar's businesses. We handle the technology so you can focus on growth.
            </p>
            <div style={{ display: 'flex', gap: 12 }}>
              <a href="https://www.linkedin.com/company/cloudwise-gibraltar" aria-label="LinkedIn" target="_blank" rel="noopener" style={{
                width: 38, height: 38, borderRadius: 999, background: 'rgba(255,255,255,0.06)',
                display: 'grid', placeItems: 'center', color: '#fff', textDecoration: 'none',
                transition: 'background 150ms',
              }} onMouseEnter={e => e.currentTarget.style.background = 'var(--cw-sky-500)'}
                 onMouseLeave={e => e.currentTarget.style.background = 'rgba(255,255,255,0.06)'}>
                <Icon.linkedin />
              </a>
              <a href="https://www.facebook.com/CloudWiseGib" aria-label="Facebook" target="_blank" rel="noopener" style={{
                width: 38, height: 38, borderRadius: 999, background: 'rgba(255,255,255,0.06)',
                display: 'grid', placeItems: 'center', color: '#fff', textDecoration: 'none',
                transition: 'background 150ms',
              }} onMouseEnter={e => e.currentTarget.style.background = 'var(--cw-sky-500)'}
                 onMouseLeave={e => e.currentTarget.style.background = 'rgba(255,255,255,0.06)'}>
                <Icon.facebook />
              </a>
            </div>
          </div>
          {cols.map(col => (
            <div key={col.title}>
              <div style={{ fontWeight: 700, color: '#fff', marginBottom: 18, fontSize: 14, letterSpacing: '0.05em', textTransform: 'uppercase' }}>{col.title}</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                {col.links.map(l => (
                  <Link key={l.label} to={l.to} style={{ color: 'var(--cw-navy-200)', fontSize: 14, textDecoration: 'none', transition: 'color 150ms' }}
                    onMouseEnter={e => e.currentTarget.style.color = 'var(--cw-sky-300)'}
                    onMouseLeave={e => e.currentTarget.style.color = 'var(--cw-navy-200)'}>
                    {l.label}
                  </Link>
                ))}
              </div>
            </div>
          ))}
          <div>
            <div style={{ fontWeight: 700, color: '#fff', marginBottom: 18, fontSize: 14, letterSpacing: '0.05em', textTransform: 'uppercase' }}>Get in touch</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <a href="mailto:hello@cloudwise.gi" style={{ display: 'flex', alignItems: 'center', gap: 10, color: '#fff', fontSize: 14, textDecoration: 'none' }}>
                <Icon.mail style={{ color: 'var(--cw-sky-400)' }} /> hello@cloudwise.gi
              </a>
              <a href="tel:+35022502143" style={{ display: 'flex', alignItems: 'center', gap: 10, color: '#fff', fontSize: 14, textDecoration: 'none' }}>
                <Icon.phone style={{ color: 'var(--cw-sky-400)' }} /> +350 225 02143
              </a>
              <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, color: 'var(--cw-navy-200)', fontSize: 14 }}>
                <Icon.pin style={{ color: 'var(--cw-sky-400)', flexShrink: 0, marginTop: 2 }} />
                <span>22 City Mill Lane,<br/>Gibraltar GX11 1AA</span>
              </div>
            </div>
          </div>
        </div>
        <div style={{
          paddingTop: 28, borderTop: '1px solid rgba(255,255,255,0.08)',
          display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 16,
          fontSize: 13, color: 'var(--cw-navy-300)',
        }}>
          <div>&copy; 2026 Cloud Wise Technologies &mdash; BL257414</div>
          <div style={{ display: 'flex', gap: 24 }}>
            <a href="#" style={{ color: 'var(--cw-navy-300)', textDecoration: 'none' }}>Privacy</a>
            <a href="#" style={{ color: 'var(--cw-navy-300)', textDecoration: 'none' }}>Terms</a>
            <a href="#" style={{ color: 'var(--cw-navy-300)', textDecoration: 'none' }}>Cookies</a>
          </div>
        </div>
      </div>
      <style>{`
        @media (max-width: 900px) {
          .footer-grid { grid-template-columns: 1fr 1fr !important; }
        }
        @media (max-width: 560px) {
          .footer-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </footer>
  );
}

function QuoteBar({ onClick }) {
  const [show, setShow] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setShow(window.scrollY > 400);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <button className={'quote-bar' + (show ? ' show' : '')} onClick={onClick} aria-label="Get a free quote">
      <span className="pulse">
        <Icon.spark style={{ position: 'relative', zIndex: 1, color: '#fff', width: 16, height: 16 }} />
      </span>
      <span>Get a free quote</span>
      <Icon.arrow />
    </button>
  );
}

function ContactModal({ open, onClose }) {
  const [submitted, setSubmitted] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState(null);
  React.useEffect(() => {
    if (!open) { setSubmitted(false); setError(null); }
    if (open) {
      const onKey = (e) => { if (e.key === 'Escape') onClose(); };
      window.addEventListener('keydown', onKey);
      document.body.style.overflow = 'hidden';
      return () => { window.removeEventListener('keydown', onKey); document.body.style.overflow = ''; };
    }
  }, [open]);
  if (!open) return null;

  const handleSubmit = async (e) => {
    e.preventDefault();
    setSubmitting(true);
    setError(null);
    try {
      await submitToFormspree(new FormData(e.target));
      setSubmitted(true);
    } catch {
      setError('Something went wrong. Please try again or call us directly.');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 100,
      background: 'rgba(10, 14, 44, 0.55)',
      backdropFilter: 'blur(6px)',
      display: 'grid', placeItems: 'center', padding: 20,
      animation: 'pageIn 240ms var(--ease-out)',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        background: '#fff', borderRadius: 'var(--radius-2xl)',
        maxWidth: 520, width: '100%', padding: 36,
        boxShadow: 'var(--shadow-xl)', position: 'relative',
        maxHeight: '90vh', overflow: 'auto',
      }}>
        <button onClick={onClose} aria-label="Close" style={{
          position: 'absolute', top: 16, right: 16, background: 'transparent',
          border: 'none', cursor: 'pointer', color: 'var(--fg-3)', padding: 8,
        }}><Icon.close /></button>

        {submitted ? (
          <div style={{ textAlign: 'center', padding: '24px 0' }}>
            <div style={{
              width: 64, height: 64, borderRadius: '50%',
              background: 'var(--cw-sky-50)', color: 'var(--cw-sky-600)',
              display: 'grid', placeItems: 'center', margin: '0 auto 20px',
            }}><Icon.check style={{ width: 32, height: 32 }} /></div>
            <h3 style={{ marginBottom: 12 }}>Thanks &mdash; we'll be in touch.</h3>
            <p style={{ color: 'var(--fg-3)' }}>One of our team will reply within one business day. In the meantime, feel free to call us on +350 225 02143.</p>
            <button className="btn btn-outline" style={{ marginTop: 20 }} onClick={onClose}>Close</button>
          </div>
        ) : (
          <>
            <div className="eyebrow" style={{ marginBottom: 12 }}>Get a free quote</div>
            <h3 style={{ marginBottom: 8 }}>Tell us about your business.</h3>
            <p style={{ color: 'var(--fg-3)', marginBottom: 24, fontSize: 15 }}>
              No obligation &mdash; we'll review your needs and reply with a clear, costed proposal.
            </p>
            <form onSubmit={handleSubmit} style={{ display: 'grid', gap: 14 }}>
              <input type="hidden" name="_form_type" value="Quote Request" />
              <div className="field"><label>Full name</label><input name="name" required placeholder="Jane Smith" /></div>
              <div className="field-row" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
                <div className="field"><label>Email</label><input name="email" required type="email" placeholder="jane@company.com" /></div>
                <div className="field"><label>Phone</label><input name="phone" type="tel" placeholder="+350 ..." /></div>
              </div>
              <div className="field">
                <label>Service of interest</label>
                <select name="service">
                  <option>Not sure &mdash; recommend something</option>
                  {SERVICES.map(s => <option key={s.slug}>{s.title}</option>)}
                </select>
              </div>
              <div className="field"><label>What can we help with?</label><textarea name="message" placeholder="Tell us a bit about your business and what you're looking for..." /></div>
              {error && <div style={{ color: 'var(--cw-danger)', fontSize: 14, textAlign: 'center' }}>{error}</div>}
              <button type="submit" className="btn btn-primary" style={{ marginTop: 8, opacity: submitting ? 0.7 : 1 }} disabled={submitting}>
                {submitting ? 'Sending...' : 'Send enquiry'} {!submitting && <Icon.arrow />}
              </button>
              <div style={{ fontSize: 12, color: 'var(--fg-4)', textAlign: 'center' }}>
                We'll only use your details to reply. No marketing, ever.
              </div>
            </form>
          </>
        )}
      </div>
    </div>
  );
}

window.Header = Header;
window.Footer = Footer;
window.QuoteBar = QuoteBar;
window.ContactModal = ContactModal;