const { Badge, Button } = window.HisabCheckAccountancyDesignSystem_95b7f0;
const SD = window.SiteData;

function fadeInDecoded(e) {
  const img = e.currentTarget;
  const show = () => { img.style.opacity = 1; };
  if (img.decode) img.decode().then(show).catch(show); else show();
}

// Ref callback: images already loaded from the preload cache before React
// mounts never fire onLoad, so reveal them immediately.
function fadeInRef(el) {
  if (el && el.complete && el.naturalWidth) el.style.opacity = 1;
}

function BrandLogo({ height = 76 }) {
  return <a href="index.html" style={{ display: 'flex', alignItems: 'center' }}><img src="hisabcheck-2--ms7d3nq4-1v58.png" alt="HisabCheck Accountancy" width={199} height={height} decoding="async" fetchpriority="high" style={{ height, width: 199, borderRadius: 10, display: 'block', opacity: 0, transition: 'opacity .25s ease' }} onLoad={fadeInDecoded} ref={fadeInRef} /></a>;
}

const SOCIAL_PATHS = {
  instagram: <path d="M12 2.2c-2.7 0-3 0-4.1.06-1.1.05-1.85.23-2.5.48a5 5 0 0 0-1.82 1.18A5 5 0 0 0 2.4 5.74c-.26.66-.44 1.4-.49 2.5C1.85 9.35 1.85 9.7 1.85 12s0 2.65.06 3.76c.05 1.1.23 1.84.49 2.5.27.68.62 1.26 1.18 1.82a5 5 0 0 0 1.82 1.18c.66.26 1.4.44 2.5.49 1.1.06 1.4.06 4.1.06s3-.0 4.1-.06c1.1-.05 1.85-.23 2.5-.49a5 5 0 0 0 1.82-1.18 5 5 0 0 0 1.18-1.82c.26-.66.44-1.4.49-2.5.06-1.1.06-1.4.06-3.76s0-2.65-.06-3.76c-.05-1.1-.23-1.84-.49-2.5a5 5 0 0 0-1.18-1.82A5 5 0 0 0 18.6 2.74c-.66-.26-1.4-.44-2.5-.49C15 2.2 14.7 2.2 12 2.2Zm0 1.8c2.65 0 2.97 0 4.02.06.97.04 1.5.2 1.85.34.46.18.79.4 1.14.74.34.35.56.68.74 1.14.14.35.3.88.34 1.85.06 1.05.06 1.37.06 4.02s0 2.97-.06 4.02c-.04.97-.2 1.5-.34 1.85-.18.46-.4.79-.74 1.14-.35.34-.68.56-1.14.74-.35.14-.88.3-1.85.34-1.05.06-1.37.06-4.02.06s-2.97 0-4.02-.06c-.97-.04-1.5-.2-1.85-.34a3.2 3.2 0 0 1-1.14-.74 3.2 3.2 0 0 1-.74-1.14c-.14-.35-.3-.88-.34-1.85-.06-1.05-.06-1.37-.06-4.02s0-2.97.06-4.02c.04-.97.2-1.5.34-1.85.18-.46.4-.79.74-1.14.35-.34.68-.56 1.14-.74.35-.14.88-.3 1.85-.34C9.03 4 9.35 4 12 4Zm0 3.05a4.95 4.95 0 1 0 0 9.9 4.95 4.95 0 0 0 0-9.9Zm0 8.17a3.22 3.22 0 1 1 0-6.44 3.22 3.22 0 0 1 0 6.44Zm6.3-8.37a1.16 1.16 0 1 1-2.31 0 1.16 1.16 0 0 1 2.31 0Z" />,
  facebook: <path d="M13.5 22v-8.4h2.8l.42-3.27h-3.22V8.24c0-.95.26-1.6 1.63-1.6h1.74V3.7A23.4 23.4 0 0 0 14.3 3.5c-2.5 0-4.22 1.53-4.22 4.33v2.5H7.3v3.27h2.78V22h3.42Z" />,
  linkedin: <path d="M4.98 3.5a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5ZM3.2 8.98h3.56V21H3.2V8.98Zm6.35 0h3.4v1.64h.05c.48-.9 1.64-1.85 3.38-1.85 3.62 0 4.28 2.38 4.28 5.48V21h-3.55v-5.9c0-1.4-.03-3.2-1.95-3.2-1.96 0-2.26 1.53-2.26 3.1V21H9.55V8.98Z" />,
  youtube: <path d="M21.6 7.4a2.8 2.8 0 0 0-2-2C17.9 5 12 5 12 5s-5.9 0-7.6.4a2.8 2.8 0 0 0-2 2A29 29 0 0 0 2 12a29 29 0 0 0 .4 4.6 2.8 2.8 0 0 0 2 2C6.1 19 12 19 12 19s5.9 0 7.6-.4a2.8 2.8 0 0 0 2-2A29 29 0 0 0 22 12a29 29 0 0 0-.4-4.6ZM10 15.2V8.8l5.5 3.2-5.5 3.2Z" />,
  whatsapp: <path d="M12 2C6.48 2 2 6.48 2 12c0 1.85.5 3.58 1.36 5.07L2 22l5.07-1.36A9.94 9.94 0 0 0 12 22c5.52 0 10-4.48 10-10S17.52 2 12 2zm5.2 14.2c-.22.62-1.28 1.19-1.77 1.24-.47.05-.9.23-3.02-.63-2.56-1.04-4.19-3.7-4.32-3.87-.13-.17-1.03-1.37-1.03-2.62 0-1.24.65-1.85.88-2.1.23-.25.5-.31.67-.31h.48c.15 0 .36-.06.56.43.22.55.74 1.88.8 2.02.06.13.1.29.02.46-.08.17-.13.27-.25.42-.13.15-.27.33-.38.44-.13.13-.26.27-.11.53.15.26.67 1.1 1.43 1.78 1 .89 1.83 1.17 2.09 1.3.27.13.42.11.58-.07.16-.18.68-.79.86-1.06.18-.27.36-.22.6-.13.25.09 1.57.74 1.84.87.27.13.45.2.51.31.07.11.07.66-.15 1.28z" />,
  x: <path d="M13.62 10.6 20.1 3h-1.54l-5.63 6.55L8.44 3H3.2l6.8 9.9L3.2 21h1.54l5.95-6.92L15.56 21h5.24l-7.18-10.4Zm-2.1 2.45-.69-.99L5.5 4.2h2.36l4.42 6.33.69.99 5.85 8.38h-2.36l-4.94-7.85Z" />,
};
const SOCIAL_ORDER = ['whatsapp', 'instagram', 'facebook', 'x', 'linkedin', 'youtube'];
function socialHref(key) { return key === 'whatsapp' ? SD.brand.whatsappCtaLink : (key === 'x' ? 'https://x.com/hisabcheck?s=11' : SD.brand.social[key]); }

function SocialIcon({ pathKey, href, label, theme = 'dark' }) {
  const dark = theme === 'dark';
  return (
    <a href={href} target={pathKey === 'whatsapp' ? undefined : '_blank'} rel="noopener noreferrer" aria-label={label} style={{ width: dark ? 36 : 32, height: dark ? 36 : 32, borderRadius: '50%', background: dark ? 'rgba(255,255,255,0.08)' : 'var(--color-accent-soft)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: dark ? '#fff' : 'var(--color-accent-primary)' }}>
      <svg width={dark ? 16 : 15} height={dark ? 16 : 15} viewBox="0 0 24 24" fill="currentColor">{SOCIAL_PATHS[pathKey]}</svg>
    </a>
  );
}
function SocialRow({ theme = 'dark' }) {
  return <div style={{ display: 'flex', gap: theme === 'dark' ? 12 : 8 }}>{SOCIAL_ORDER.map(k => <SocialIcon key={k} pathKey={k} href={socialHref(k)} label={k} theme={theme} />)}</div>;
}

function BrandNavbar({ activeLink }) {
  const [scrolled, setScrolled] = React.useState(false);
  const [open, setOpen] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  const linkHref = l => l === 'FAQs' ? 'faqs.html' : (l.toLowerCase() + '.html');
  return (
    <header style={{ position: 'sticky', top: 0, zIndex: 40, transition: 'all var(--dur-fast) var(--ease-standard)', background: scrolled || open ? 'rgba(255,255,255,0.92)' : 'transparent', backdropFilter: scrolled || open ? 'var(--blur-nav)' : 'none', borderBottom: scrolled || open ? '1px solid var(--color-border)' : '1px solid transparent' }}>
      <div style={{ maxWidth: 'var(--max-width)', margin: '0 auto', padding: '14px 24px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <BrandLogo />
        <nav className="brand-nav-links" style={{ display: 'flex', gap: 30 }}>
          {SD.navLinks.filter(l => l !== 'Contact').map(l => (
            <a key={l} href={linkHref(l)} style={{ fontFamily: 'var(--font-body)', fontSize: 'var(--fs-body)', fontWeight: 'var(--fw-medium)', color: l === activeLink ? 'var(--color-accent-primary)' : 'var(--color-text-primary)', paddingBottom: 4, borderBottom: l === activeLink ? '2px solid var(--color-accent-primary)' : '2px solid transparent' }}>{l}</a>
          ))}
        </nav>
        <div className="brand-nav-links" style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
          <a href="contact.html" style={{ background: 'var(--color-accent-primary)', color: '#fff', border: 'none', fontWeight: 'var(--fw-semibold)', padding: '11px 22px', borderRadius: 'var(--radius-pill)', fontFamily: 'var(--font-body)', textDecoration: 'none', fontSize: 'var(--fs-small)', whiteSpace: 'nowrap' }}>Book free consultation</a>
        </div>
        <button className="mobile-menu-btn" onClick={() => setOpen(o => !o)} aria-label="Toggle menu" style={{ display: 'none', border: 'none', background: 'none', cursor: 'pointer', width: 48, height: 48, alignItems: 'center', justifyContent: 'center' }}>
          <svg width="31" height="31" viewBox="0 0 24 24" fill="none" stroke="var(--color-text-primary)" strokeWidth="2" strokeLinecap="round">{open ? <path d="M5 5l14 14M19 5L5 19" /> : <path d="M4 7h16M4 12h16M4 17h16" />}</svg>
        </button>
      </div>
      {open && (
        <div style={{ borderTop: '1px solid var(--color-border)', padding: '16px 24px 24px', display: 'flex', flexDirection: 'column', gap: 16, background: '#fff' }}>
          {SD.navLinks.filter(l => l !== 'Contact').map(l => <a key={l} href={linkHref(l)} style={{ fontFamily: 'var(--font-body)', fontWeight: 'var(--fw-medium)', color: l === activeLink ? 'var(--color-accent-primary)' : 'var(--color-text-primary)' }}>{l}</a>)}
          <a href="contact.html" style={{ background: 'var(--color-accent-primary)', color: '#fff', textAlign: 'center', padding: '12px 0', borderRadius: 'var(--radius-pill)', fontFamily: 'var(--font-body)', fontWeight: 'var(--fw-semibold)' }}>Book free consultation</a>
        </div>
      )}
    </header>
  );
}

function BrandFooter() {
  const columns = [
    { title: 'Services', links: [['Self Assessment', 'service-self-assessment.html'], ['Limited Company Accounts', 'service-limited-company-accounts.html'], ['Bookkeeping', 'service-bookkeeping.html'], ['Payroll', 'service-payroll.html'], ['VAT Returns', 'service-vat.html']] },
    { title: 'Company', links: [['About Us', 'about.html'], ['Pricing', 'pricing.html'], ['Resources', 'resources.html'], ['Contact', 'contact.html']] },
    { title: 'Legal', links: [['Privacy Policy', 'privacy.html'], ['Terms & Conditions', 'terms.html'], ['Cookie Policy', 'cookies.html']] },
  ];
  return (
    <footer style={{ background: 'var(--gray-900)', color: 'var(--gray-300)', padding: '80px 24px 32px' }}>
      <div style={{ maxWidth: 'var(--max-width)', margin: '0 auto' }}>
        <div className="brand-footer-grid" style={{ display: 'grid', gridTemplateColumns: '1.4fr repeat(3, 1fr)', gap: 40 }}>
          <div>
            <div style={{ marginBottom: 16 }}><img src="hisabcheck-2--ms7d3nq4-1v58.png" alt="HisabCheck Accountancy" width={154} height={60} loading="lazy" decoding="async" style={{ height: 60, width: 154, borderRadius: 8, display: 'block', opacity: 0, transition: 'opacity .25s ease' }} onLoad={fadeInDecoded} ref={fadeInRef} /></div>
            <p style={{ fontFamily: 'var(--font-body)', fontSize: 'var(--fs-small)', lineHeight: 'var(--lh-body)', maxWidth: 260, margin: 0 }}>Modern, digital-first accounting for UK businesses — remote consultations, secure document sharing and clear, upfront pricing.</p>
            <p style={{ fontFamily: 'var(--font-body)', fontSize: 'var(--fs-small)', marginTop: 14 }}>Location: United Kingdom | India</p>
            <div style={{ marginTop: 20 }}><SocialRow /></div>
          </div>
          {columns.map(col => (
            <div key={col.title}>
              <div style={{ color: '#fff', fontWeight: 'var(--fw-semibold)', marginBottom: 16, fontFamily: 'var(--font-body)' }}>{col.title}</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {col.links.map(([label, href]) => <a key={label} href={href} style={{ color: 'var(--gray-300)', fontSize: 'var(--fs-small)' }}>{label}</a>)}
              </div>
            </div>
          ))}
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderTop: '1px solid rgba(255,255,255,0.1)', marginTop: 56, paddingTop: 24, fontSize: 'var(--fs-tiny)', flexWrap: 'wrap', gap: 12 }}>
          <span>© 2026 HisabCheck Accountancy. All rights reserved.</span>
          <div style={{ display: 'flex', gap: 20 }}>
            <a href="privacy.html" style={{ color: 'var(--gray-300)' }}>Privacy Policy</a>
            <a href="terms.html" style={{ color: 'var(--gray-300)' }}>Terms & Conditions</a>
            <a href="cookies.html" style={{ color: 'var(--gray-300)' }}>Cookie Policy</a>
            <a href="admin.html" style={{ color: 'var(--gray-300)' }}>Admin</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

function BrandWhatsAppButton() {
  const [visible, setVisible] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setVisible(window.scrollY > 220);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <a href={SD.brand.whatsappCtaLink} rel="noopener noreferrer" style={{ position: 'fixed', bottom: 24, right: 24, zIndex: 50, display: 'flex', alignItems: 'center', gap: 10, background: 'var(--color-accent-green)', color: '#fff', padding: '14px 20px', borderRadius: 'var(--radius-pill)', boxShadow: 'var(--shadow-float)', fontFamily: 'var(--font-body)', fontWeight: 'var(--fw-semibold)', textDecoration: 'none', opacity: visible ? 1 : 0, transform: visible ? 'translateY(0)' : 'translateY(12px)', pointerEvents: visible ? 'auto' : 'none', transition: 'opacity var(--dur-fast) var(--ease-standard), transform var(--dur-fast) var(--ease-standard), background var(--dur-fast) var(--ease-standard)' }}
      onMouseEnter={e => e.currentTarget.style.background = 'var(--color-accent-green-hover)'}
      onMouseLeave={e => e.currentTarget.style.background = 'var(--color-accent-green)'}>
      <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C6.48 2 2 6.48 2 12c0 1.85.5 3.58 1.36 5.07L2 22l5.07-1.36A9.94 9.94 0 0 0 12 22c5.52 0 10-4.48 10-10S17.52 2 12 2zm5.2 14.2c-.22.62-1.28 1.19-1.77 1.24-.47.05-.9.23-3.02-.63-2.56-1.04-4.19-3.7-4.32-3.87-.13-.17-1.03-1.37-1.03-2.62 0-1.24.65-1.85.88-2.1.23-.25.5-.31.67-.31h.48c.15 0 .36-.06.56.43.22.55.74 1.88.8 2.02.06.13.1.29.02.46-.08.17-.13.27-.25.42-.13.15-.27.33-.38.44-.13.13-.26.27-.11.53.15.26.67 1.1 1.43 1.78 1 .89 1.83 1.17 2.09 1.3.27.13.42.11.58-.07.16-.18.68-.79.86-1.06.18-.27.36-.22.6-.13.25.09 1.57.74 1.84.87.27.13.45.2.51.31.07.11.07.66-.15 1.28z" /></svg>
      Chat on WhatsApp
    </a>
  );
}

function Field({ label, type = 'text', name, textarea, value, onChange, required }) {
  const [focused, setFocused] = React.useState(false);
  const filled = value && value.length > 0;
  const Comp = textarea ? 'textarea' : 'input';
  return (
    <div style={{ position: 'relative' }}>
      <Comp type={type} name={name} value={value} onChange={onChange} rows={textarea ? 4 : undefined} required={required}
        onFocus={() => setFocused(true)} onBlur={() => setFocused(false)}
        style={{ width: '100%', padding: textarea ? '22px 16px 10px' : '20px 16px 8px', borderRadius: 'var(--radius-input)', border: `1.5px solid ${focused ? 'var(--color-accent-primary)' : 'var(--color-border)'}`, fontFamily: 'var(--font-body)', fontSize: 'var(--fs-body)', color: 'var(--color-text-primary)', outline: 'none', boxShadow: focused ? 'var(--shadow-focus)' : 'none', transition: 'all var(--dur-fast) var(--ease-standard)', resize: textarea ? 'vertical' : 'none', boxSizing: 'border-box' }} />
      <label style={{ position: 'absolute', left: 16, top: (focused || filled) ? 6 : (textarea ? 16 : '50%'), transform: (focused || filled) ? 'none' : (textarea ? 'none' : 'translateY(-50%)'), fontSize: (focused || filled) ? 'var(--fs-tiny)' : 'var(--fs-body)', color: focused ? 'var(--color-accent-primary)' : 'var(--color-text-secondary)', fontFamily: 'var(--font-body)', transition: 'all var(--dur-fast) var(--ease-standard)', pointerEvents: 'none', background: '#fff', padding: '0 2px' }}>{label}</label>
    </div>
  );
}

const COUNTRY_CODES = [
  { code: 'GB', dial: '44', name: 'United Kingdom', flag: '🇬🇧' },
  { code: 'IN', dial: '91', name: 'India', flag: '🇮🇳' },
  { code: 'US', dial: '1', name: 'United States', flag: '🇺🇸' },
  { code: 'CA', dial: '1', name: 'Canada', flag: '🇨🇦' },
  { code: 'AU', dial: '61', name: 'Australia', flag: '🇦🇺' },
  { code: 'IE', dial: '353', name: 'Ireland', flag: '🇮🇪' },
  { code: 'NZ', dial: '64', name: 'New Zealand', flag: '🇳🇿' },
  { code: 'ZA', dial: '27', name: 'South Africa', flag: '🇿🇦' },
  { code: 'AE', dial: '971', name: 'United Arab Emirates', flag: '🇦🇪' },
  { code: 'PK', dial: '92', name: 'Pakistan', flag: '🇵🇰' },
  { code: 'BD', dial: '880', name: 'Bangladesh', flag: '🇧🇩' },
  { code: 'DE', dial: '49', name: 'Germany', flag: '🇩🇪' },
  { code: 'FR', dial: '33', name: 'France', flag: '🇫🇷' },
  { code: 'ES', dial: '34', name: 'Spain', flag: '🇪🇸' },
  { code: 'IT', dial: '39', name: 'Italy', flag: '🇮🇹' },
  { code: 'NL', dial: '31', name: 'Netherlands', flag: '🇳🇱' },
  { code: 'SG', dial: '65', name: 'Singapore', flag: '🇸🇬' },
  { code: 'AE', dial: '966', name: 'Saudi Arabia', flag: '🇸🇦' },
  { code: 'NG', dial: '234', name: 'Nigeria', flag: '🇳🇬' },
  { code: 'KE', dial: '254', name: 'Kenya', flag: '🇰🇪' },
];

function PhoneInput({ value, onChange, error }) {
  const [country, setCountry] = React.useState(COUNTRY_CODES[0]);
  const [open, setOpen] = React.useState(false);
  const [query, setQuery] = React.useState('');
  const wrapRef = React.useRef(null);
  React.useEffect(() => {
    const onDoc = e => { if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, []);
  const national = value.replace(/^\+\d+\s*/, '');
  React.useEffect(() => { if (national) onChange(`+${country.dial} ${national}`); }, [country]);
  const filtered = COUNTRY_CODES.filter(c => c.name.toLowerCase().includes(query.toLowerCase()) || c.dial.includes(query));
  const setNational = n => onChange(n ? `+${country.dial} ${n}` : '');
  return (
    <div ref={wrapRef} style={{ position: 'relative' }}>
      <div style={{ display: 'flex', border: `1.5px solid ${error ? 'var(--color-error)' : 'var(--color-border)'}`, borderRadius: 'var(--radius-input)', overflow: 'hidden', background: '#fff' }}>
        <button type="button" onClick={() => setOpen(o => !o)} style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '0 12px', border: 'none', borderRight: '1.5px solid var(--color-border)', background: 'transparent', fontFamily: 'var(--font-body)', fontSize: 'var(--fs-body)', cursor: 'pointer' }}>
          <span style={{ fontSize: 18 }}>{country.flag}</span><span style={{ color: 'var(--color-text-secondary)' }}>+{country.dial}</span>
          <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3"><path d="M4 8l8 8 8-8" /></svg>
        </button>
        <input value={national} onChange={e => setNational(e.target.value.replace(/[^\d\s]/g, ''))} placeholder="e.g. 7123 456789" style={{ flex: 1, padding: '14px 16px', border: 'none', outline: 'none', fontFamily: 'var(--font-body)', fontSize: 'var(--fs-body)', minWidth: 0 }} />
      </div>
      {error && <div style={{ color: 'var(--color-error)', fontSize: 'var(--fs-tiny)', marginTop: 6, fontFamily: 'var(--font-body)' }}>{error}</div>}
      {open && (
        <div style={{ position: 'absolute', top: '100%', left: 0, marginTop: 6, width: 'min(280px, calc(100vw - 72px))', maxWidth: 280, maxHeight: 280, overflowY: 'auto', background: '#fff', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-card)', boxShadow: 'var(--shadow-float)', zIndex: 30 }}>
          <div style={{ padding: 10, position: 'sticky', top: 0, background: '#fff', borderBottom: '1px solid var(--color-border)' }}>
            <input autoFocus value={query} onChange={e => setQuery(e.target.value)} placeholder="Search country or code" style={{ width: '100%', padding: '8px 10px', borderRadius: 8, border: '1px solid var(--color-border)', fontFamily: 'var(--font-body)', fontSize: 'var(--fs-small)', boxSizing: 'border-box' }} />
          </div>
          {filtered.map((c, i) => (
            <div key={c.name + i} onClick={() => { setCountry(c); setOpen(false); setQuery(''); }} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '9px 14px', cursor: 'pointer', fontFamily: 'var(--font-body)', fontSize: 'var(--fs-small)' }}
              onMouseEnter={e => e.currentTarget.style.background = 'var(--color-bg-page)'} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
              <span style={{ fontSize: 16 }}>{c.flag}</span><span style={{ flex: 1 }}>{c.name}</span><span style={{ color: 'var(--color-text-secondary)' }}>+{c.dial}</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function SuccessNote({ title, description }) {
  return (
    <div style={{ textAlign: 'center', padding: 40 }}>
      <div style={{ width: 56, height: 56, borderRadius: '50%', background: 'var(--color-success-bg)', color: 'var(--color-success)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 28, margin: '0 auto 16px' }}>✓</div>
      <div style={{ fontFamily: 'var(--font-display)', fontWeight: 'var(--fw-semibold)', fontSize: 'var(--fs-h4)' }}>{title}</div>
      <p style={{ fontFamily: 'var(--font-body)', color: 'var(--color-text-secondary)' }}>{description}</p>
    </div>
  );
}

function BrandConsultationForm() {
  const services = SD.services.map(s => s.title);
  const [service, setService] = React.useState(services[0]);
  const [name, setName] = React.useState('');
  const [phone, setPhone] = React.useState('');
  const [error, setError] = React.useState('');
  const [status, setStatus] = React.useState('idle');
  const submit = e => {
    e.preventDefault();
    if (phone.replace(/\D/g, '').length < 7) { setError('Enter a valid phone number'); return; }
    setError(''); setStatus('success');
    window.open(SD.brand.whatsappCtaLink, '_self');
  };
  if (status === 'success') return <SuccessNote title="Consultation requested" description="We’ve opened WhatsApp — send the message to confirm and a member of our team will reply shortly." />;
  return (
    <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      <Field label="Full name" name="name" value={name} onChange={e => setName(e.target.value)} required />
      <div>
        <label style={{ fontFamily: 'var(--font-body)', fontSize: 'var(--fs-small)', fontWeight: 'var(--fw-semibold)', color: 'var(--color-text-primary)' }}>Service needed</label>
        <select value={service} onChange={e => setService(e.target.value)} style={{ width: '100%', marginTop: 8, padding: '14px 16px', borderRadius: 'var(--radius-input)', border: '1.5px solid var(--color-border)', fontFamily: 'var(--font-body)', fontSize: 'var(--fs-body)', color: 'var(--color-text-primary)', boxSizing: 'border-box' }}>
          {services.map(s => <option key={s}>{s}</option>)}
        </select>
      </div>
      <div>
        <input value={phone} onChange={e => setPhone(e.target.value)} placeholder="Phone number" style={{ width: '100%', padding: '14px 16px', borderRadius: 'var(--radius-input)', border: `1.5px solid ${error ? 'var(--color-error)' : 'var(--color-border)'}`, fontFamily: 'var(--font-body)', fontSize: 'var(--fs-body)', boxSizing: 'border-box' }} />
        {error && <div style={{ color: 'var(--color-error)', fontSize: 'var(--fs-tiny)', marginTop: 6, fontFamily: 'var(--font-body)' }}>{error}</div>}
      </div>
      <button type="submit" style={{ background: 'var(--color-accent-green)', color: '#fff', border: 'none', padding: '15px 0', borderRadius: 'var(--radius-button)', fontFamily: 'var(--font-body)', fontWeight: 'var(--fw-semibold)', cursor: 'pointer' }}>Book free consultation</button>
    </form>
  );
}

const CONTACT_SERVICES = ['Self Assessment Tax Return','Limited Company Accounts','Corporation Tax','VAT Registration & Returns','Bookkeeping','Payroll','Company Formation','Confirmation Statement','Capital Gains Tax','CIS Returns','Tax Planning','Business Advisory','Year End Accounts','Other'];

function BrandUnifiedContactForm() {
  const [form, setForm] = React.useState({ name: '', email: '', phone: '', service: CONTACT_SERVICES[0], message: '' });
  const [errors, setErrors] = React.useState({});
  const [status, setStatus] = React.useState('idle');
  const [emailError, setEmailError] = React.useState('');
  const hpRef = React.useRef(null);
  const mountedAt = React.useRef(Date.now());
  const set = k => e => setForm(f => ({ ...f, [k]: e.target.value }));
  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = 'Name is required';
    if (!form.email.trim() || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) e.email = 'Valid email is required';
    if (!form.service) e.service = 'Please select a service';
    if (!form.message.trim()) e.message = 'Please add a short message';
    setErrors(e);
    return Object.keys(e).length === 0;
  };
  const buildMessage = () => `Hello HisabCheck,\n\nI would like a free consultation.\n\nName: ${form.name}\nEmail: ${form.email}${form.phone ? `\nPhone: ${form.phone}` : ''}\n\nService:\n${form.service}\n\nMessage:\n${form.message}\n\nSubmitted from:\nhisabcheck.com`;
  const buildEmailBody = () => `Hello HisabCheck,\n\nI would like a free consultation.\n\nName:\n${form.name}\n\nEmail:\n${form.email}${form.phone ? `\n\nPhone:\n${form.phone}` : ''}\n\nService:\n${form.service}\n\nMessage:\n${form.message}\n\nSubmitted from:\nhisabcheck.com`;
  const sendWhatsApp = () => {
    if (!validate()) return;
    const url = `${SD.brand.whatsappLink}?text=${encodeURIComponent(buildMessage())}`;
    window.open(url, '_self');
    setStatus('success');
  };
  const sendEmail = async () => {
    if (!validate()) return;
    setStatus('sending');
    setEmailError('');
    try {
      const res = await fetch('send-email.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...form, hp: hpRef.current ? hpRef.current.value : '', elapsed: Date.now() - mountedAt.current }),
      });
      const data = await res.json().catch(() => ({}));
      if (res.ok && data.success) { setStatus('success'); }
      else { setStatus('error'); setEmailError(data.error || 'Something went wrong sending your message. Please try WhatsApp instead or email us directly.'); }
    } catch (err) {
      setStatus('error');
      setEmailError('Could not reach the server. Please try WhatsApp instead or email us directly.');
    }
  };
  if (status === 'success') return <SuccessNote title="Message sent" description="Thanks — your enquiry has been emailed to our team. We reply within one business day." />;
  const errStyle = { border: '1.5px solid var(--color-error)' };
  return (
    <form onSubmit={e => e.preventDefault()} style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      <div>
        <Field label="Full name" name="name" value={form.name} onChange={set('name')} required />
        {errors.name && <div style={{ color: 'var(--color-error)', fontSize: 'var(--fs-tiny)', marginTop: 6, fontFamily: 'var(--font-body)' }}>{errors.name}</div>}
      </div>
      <div>
        <Field label="Email address" type="email" name="email" value={form.email} onChange={set('email')} required />
        {errors.email && <div style={{ color: 'var(--color-error)', fontSize: 'var(--fs-tiny)', marginTop: 6, fontFamily: 'var(--font-body)' }}>{errors.email}</div>}
      </div>
      <div>
        <label style={{ fontFamily: 'var(--font-body)', fontSize: 'var(--fs-small)', fontWeight: 'var(--fw-semibold)', color: 'var(--color-text-primary)', display: 'block', marginBottom: 8 }}>Phone number</label>
        <PhoneInput value={form.phone} onChange={v => setForm(f => ({ ...f, phone: v }))} error={errors.phone} />
      </div>
      <div>
        <label style={{ fontFamily: 'var(--font-body)', fontSize: 'var(--fs-small)', fontWeight: 'var(--fw-semibold)', color: 'var(--color-text-primary)' }}>Service required</label>
        <select value={form.service} onChange={set('service')} style={{ width: '100%', marginTop: 8, padding: '14px 16px', borderRadius: 'var(--radius-input)', border: '1.5px solid var(--color-border)', fontFamily: 'var(--font-body)', fontSize: 'var(--fs-body)', color: 'var(--color-text-primary)', boxSizing: 'border-box' }}>
          {CONTACT_SERVICES.map(s => <option key={s}>{s}</option>)}
        </select>
      </div>
      <div>
        <Field label="Message" name="message" textarea value={form.message} onChange={set('message')} required />
        {errors.message && <div style={{ color: 'var(--color-error)', fontSize: 'var(--fs-tiny)', marginTop: 6, fontFamily: 'var(--font-body)' }}>{errors.message}</div>}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        <button type="button" onClick={sendWhatsApp} disabled={status === 'sending'} style={{ background: 'var(--color-accent-green)', color: '#fff', border: 'none', padding: '15px 0', borderRadius: 'var(--radius-button)', fontFamily: 'var(--font-body)', fontWeight: 'var(--fw-semibold)', cursor: status === 'sending' ? 'default' : 'pointer', opacity: status === 'sending' ? 0.7 : 1, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C6.48 2 2 6.48 2 12c0 1.85.5 3.58 1.36 5.07L2 22l5.07-1.36A9.94 9.94 0 0 0 12 22c5.52 0 10-4.48 10-10S17.52 2 12 2zm5.2 14.2c-.22.62-1.28 1.19-1.77 1.24-.47.05-.9.23-3.02-.63-2.56-1.04-4.19-3.7-4.32-3.87-.13-.17-1.03-1.37-1.03-2.62 0-1.24.65-1.85.88-2.1.23-.25.5-.31.67-.31h.48c.15 0 .36-.06.56.43.22.55.74 1.88.8 2.02.06.13.1.29.02.46-.08.17-.13.27-.25.42-.13.15-.27.33-.38.44-.13.13-.26.27-.11.53.15.26.67 1.1 1.43 1.78 1 .89 1.83 1.17 2.09 1.3.27.13.42.11.58-.07.16-.18.68-.79.86-1.06.18-.27.36-.22.6-.13.25.09 1.57.74 1.84.87.27.13.45.2.51.31.07.11.07.66-.15 1.28z" /></svg>
          {status === 'sending' ? 'Preparing message…' : 'Send via WhatsApp'}
        </button>
        <button type="button" onClick={sendEmail} disabled={status === 'sending'} style={{ background: 'var(--color-accent-primary)', color: '#fff', border: 'none', padding: '15px 0', borderRadius: 'var(--radius-button)', fontFamily: 'var(--font-body)', fontWeight: 'var(--fw-semibold)', cursor: status === 'sending' ? 'default' : 'pointer', opacity: status === 'sending' ? 0.7 : 1, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
          {status === 'sending' && <span style={{ width: 14, height: 14, border: '2px solid rgba(255,255,255,0.5)', borderTopColor: '#fff', borderRadius: '50%', display: 'inline-block', animation: 'hcSpin .7s linear infinite' }} />}
          {status === 'sending' ? 'Sending…' : 'Send email'}
        </button>
        {status === 'error' && <div style={{ color: 'var(--color-error)', fontSize: 'var(--fs-small)', fontFamily: 'var(--font-body)', textAlign: 'center' }}>{emailError}</div>}
        <input ref={hpRef} type="text" name="company" tabIndex={-1} autoComplete="off" style={{ position: 'absolute', width: 1, height: 1, padding: 0, margin: -1, overflow: 'hidden', clip: 'rect(0,0,0,0)', whiteSpace: 'nowrap', border: 0 }} aria-hidden="true" />
      </div>
    </form>
  );
}

function FAQAccordionItem({ q, a }) {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  return (
    <div style={{ border: '1px solid var(--color-border)', borderRadius: 'var(--radius-card)', background: '#fff', overflow: 'hidden' }}>
      <button onClick={() => setOpen(o => !o)} style={{ width: '100%', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, padding: '18px 22px', background: 'none', border: 'none', cursor: 'pointer', textAlign: 'left', fontFamily: 'var(--font-body)', fontWeight: 'var(--fw-semibold)', fontSize: 'var(--fs-body)', color: 'var(--color-text-primary)' }}>
        {q}
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--color-accent-primary)" strokeWidth="2.5" style={{ flexShrink: 0, transform: open ? 'rotate(180deg)' : 'none', transition: 'transform var(--dur-fast) var(--ease-standard)' }}><path d="M4 8l8 8 8-8" /></svg>
      </button>
      <div style={{ maxHeight: open ? (ref.current ? ref.current.scrollHeight : 400) : 0, overflow: 'hidden', transition: 'max-height var(--dur-med, 0.35s) var(--ease-standard)' }}>
        <p ref={ref} style={{ margin: 0, padding: '0 22px 20px', fontFamily: 'var(--font-body)', fontSize: 'var(--fs-body)', lineHeight: 'var(--lh-body)', color: 'var(--color-text-secondary)' }}>{a}</p>
      </div>
    </div>
  );
}

function SearchableFAQ({ categories }) {
  const [query, setQuery] = React.useState('');
  const q = query.trim().toLowerCase();
  const filtered = categories.map(cat => ({ ...cat, items: cat.items.filter(i => !q || i.q.toLowerCase().includes(q) || i.a.toLowerCase().includes(q)) })).filter(cat => cat.items.length);
  return (
    <div>
      <input value={query} onChange={e => setQuery(e.target.value)} placeholder="Search questions…" style={{ width: '100%', padding: '16px 20px', borderRadius: 'var(--radius-input)', border: '1.5px solid var(--color-border)', fontFamily: 'var(--font-body)', fontSize: 'var(--fs-body)', marginBottom: 48, boxSizing: 'border-box', boxShadow: 'var(--shadow-card)' }} />
      {filtered.length === 0 && <p style={{ fontFamily: 'var(--font-body)', color: 'var(--color-text-secondary)', textAlign: 'center' }}>No matching questions — try a different search term.</p>}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 48 }}>
        {filtered.map(cat => (
          <div key={cat.category}>
            <h3 style={{ fontSize: 'var(--fs-h3)', color: 'var(--color-text-primary)', marginBottom: 20 }}>{cat.category}</h3>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              {cat.items.map(item => <FAQAccordionItem key={item.q} q={item.q} a={item.a} />)}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function CardLink({ href, children }) {
  return <div style={{ position: 'relative', height: '100%', display: 'flex' }}>{children}<a href={href} aria-label="Learn more" style={{ position: 'absolute', inset: 0, borderRadius: 'var(--radius-card)' }} /></div>;
}

function BrandCTABanner({ title = 'Ready to simplify your accounting?', description = 'Book a free consultation and see how HisabCheck can help.', ctaLabel = 'Book your free call', href = 'contact.html' }) {
  return (
    <section style={{ maxWidth: 'var(--max-width)', margin: '0 auto', padding: '0 24px' }}>
      <div style={{ background: 'linear-gradient(120deg, var(--blue-700) 0%, var(--blue-600) 100%)', borderRadius: 'var(--radius-section)', padding: '64px 56px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 32, flexWrap: 'wrap' }}>
        <div>
          <h2 style={{ color: '#fff', fontSize: 'var(--fs-h2)' }}>{title}</h2>
          <p style={{ color: 'var(--blue-100)', fontFamily: 'var(--font-body)', fontSize: 'var(--fs-body-lg)', margin: '12px 0 0' }}>{description}</p>
        </div>
        <a href={href} style={{ background: '#fff', color: 'var(--color-accent-primary)', border: 'none', padding: '16px 30px', borderRadius: 'var(--radius-button)', fontWeight: 'var(--fw-semibold)', fontFamily: 'var(--font-body)', whiteSpace: 'nowrap' }}>{ctaLabel}</a>
      </div>
    </section>
  );
}

function BrandPricingCard({ tier, price, period = '/one-off', description, features = [], featured = false, ctaLabel = 'Get started', href = 'contact.html' }) {
  return (
    <div style={{ background: featured ? 'var(--blue-600)' : '#fff', color: featured ? '#fff' : 'var(--color-text-primary)', border: featured ? 'none' : '1px solid var(--color-border)', borderRadius: 'var(--radius-card)', padding: 32, boxShadow: featured ? 'var(--shadow-float)' : 'var(--shadow-card)', position: 'relative', display: 'flex', flexDirection: 'column' }}>
      {featured && <span style={{ position: 'absolute', top: -14, left: 32, background: 'var(--green-500)', color: '#fff', fontSize: 'var(--fs-tiny)', fontWeight: 'var(--fw-semibold)', padding: '5px 14px', borderRadius: 'var(--radius-pill)' }}>Most popular</span>}
      <div style={{ fontFamily: 'var(--font-body)', fontWeight: 'var(--fw-semibold)', color: featured ? 'var(--blue-100)' : 'var(--color-text-secondary)' }}>{tier}</div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 4, margin: '12px 0' }}>
        <span style={{ fontFamily: 'var(--font-display)', fontWeight: 'var(--fw-bold)', fontSize: 'var(--fs-display-lg)' }}>{price}</span>
        <span style={{ fontFamily: 'var(--font-body)', color: featured ? 'var(--blue-100)' : 'var(--color-text-secondary)' }}>{period}</span>
      </div>
      <p style={{ fontFamily: 'var(--font-body)', color: featured ? 'var(--blue-100)' : 'var(--color-text-secondary)', margin: '0 0 20px' }}>{description}</p>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 24, flex: 1 }}>
        {features.map(f => (
          <div key={f} style={{ display: 'flex', gap: 8, fontFamily: 'var(--font-body)', fontSize: 'var(--fs-small)' }}>
            <span style={{ color: featured ? '#fff' : 'var(--color-success)', fontWeight: 700 }}>✓</span>{f}
          </div>
        ))}
      </div>
      <a href={href} style={{ display: 'block', textAlign: 'center', width: '100%', boxSizing: 'border-box', padding: '13px 0', borderRadius: 'var(--radius-button)', border: featured ? 'none' : '1.5px solid var(--color-accent-primary)', background: featured ? '#fff' : 'transparent', color: featured ? 'var(--color-accent-primary)' : 'var(--color-accent-primary)', fontFamily: 'var(--font-body)', fontWeight: 'var(--fw-semibold)' }}>{ctaLabel}</a>
    </div>
  );
}

function FeatureImage({ id, placeholder, height = 320, style, priority = false }) {
  return <div style={{ height, borderRadius: 'var(--radius-card)', overflow: 'hidden', border: '1px solid var(--color-border)', boxShadow: 'var(--shadow-card)', background: 'var(--gray-100)', ...style }}><img src={`assets/photos/${id}.webp`} alt={placeholder || ''} loading={priority ? 'eager' : 'lazy'} decoding="async" fetchpriority={priority ? 'high' : 'auto'} style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block', opacity: 0, transition: 'opacity .25s ease' }} onLoad={fadeInDecoded} ref={fadeInRef} /></div>;
}

function PageShell({ active, children }) {
  return <div style={{ position: 'relative' }}><BrandNavbar activeLink={active} />{children}<BrandFooter /><BrandWhatsAppButton /></div>;
}

Object.assign(window, { BrandNavbar, BrandFooter, BrandWhatsAppButton, BrandUnifiedContactForm, PageShell, BrandLogo, Field, PhoneInput, SuccessNote, CardLink, BrandCTABanner, BrandPricingCard, FeatureImage, fadeInDecoded, fadeInRef, SearchableFAQ });
