/* global React */
// Shared components for behaving.co — exported to window for cross-file use.

const { useState, useEffect } = React;

// ---- Theme controller -----------------------------------------------------
function useTheme() {
  const [theme, setTheme] = useState(() => {
    if (typeof window === 'undefined') return 'light';
    return localStorage.getItem('behaving-theme') || 'light';
  });
  useEffect(() => {
    document.documentElement.setAttribute('data-theme', theme);
    localStorage.setItem('behaving-theme', theme);
  }, [theme]);
  return [theme, setTheme];
}

// ---- Logo ----------------------------------------------------------------
function Wordmark({ theme, ariaLabel = 'Behaving.co — home', href = 'index.html' }) {
  const src = theme === 'dark'
    ? 'assets/behaving-logo-dark.svg'
    : 'assets/behaving-logo-transparent.svg';
  return (
    <a href={href} className="wordmark" aria-label={ariaLabel}>
      <img src={src} alt="" width="160" height="38" />
    </a>
  );
}

// ---- Header --------------------------------------------------------------
function Header({ theme, setTheme, current }) {
  const [menuOpen, setMenuOpen] = useState(false);
  const items = [
    { href: 'services.html', label: 'Services', key: 'services' },
    { href: 'consulting.html', label: 'Consulting', key: 'consulting' },
    { href: 'about.html', label: 'About', key: 'about' },
    { href: 'contact.html', label: 'Contact', key: 'contact' },
  ];

  useEffect(() => {
    if (!menuOpen) return;
    const close = () => setMenuOpen(false);
    document.addEventListener('click', close);
    return () => document.removeEventListener('click', close);
  }, [menuOpen]);

  return (
    <header className="site-header">
      <div className="container-wide header-inner">
        <Wordmark theme={theme} />
        <nav aria-label="Primary">
          <ul className="nav-list">
            {items.map((it) => (
              <li key={it.key}>
                <a href={it.href} aria-current={current === it.key ? 'page' : undefined}>{it.label}</a>
              </li>
            ))}
          </ul>
        </nav>
        <button
          className="theme-toggle"
          aria-label={theme === 'dark' ? 'Switch to light mode' : 'Switch to dark mode'}
          onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}
        >
          {theme === 'dark' ? (
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="4"/><path d="M12 2v2"/><path d="M12 20v2"/><path d="m4.93 4.93 1.41 1.41"/><path d="m17.66 17.66 1.41 1.41"/><path d="M2 12h2"/><path d="M20 12h2"/><path d="m6.34 17.66-1.41 1.41"/><path d="m19.07 4.93-1.41 1.41"/></svg>
          ) : (
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>
          )}
        </button>
        <button
          className="menu-toggle"
          aria-label={menuOpen ? 'Close menu' : 'Open menu'}
          aria-expanded={menuOpen}
          onClick={(e) => { e.stopPropagation(); setMenuOpen((o) => !o); }}
        >
          {menuOpen ? (
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>
          ) : (
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M4 6h16"/><path d="M4 12h16"/><path d="M4 18h16"/></svg>
          )}
        </button>
      </div>
      {menuOpen && (
        <nav className="mobile-nav" aria-label="Mobile navigation" onClick={(e) => e.stopPropagation()}>
          <ul className="mobile-nav-list">
            {items.map((it) => (
              <li key={it.key}>
                <a href={it.href} aria-current={current === it.key ? 'page' : undefined}>{it.label}</a>
              </li>
            ))}
          </ul>
        </nav>
      )}
    </header>
  );
}

// ---- Button --------------------------------------------------------------
function Button({ children, variant = 'primary', href, onClick, type = 'button', disabled }) {
  const cls = `btn btn-${variant}${disabled ? ' is-disabled' : ''}`;
  if (href) {
    return <a className={cls} href={href} onClick={onClick}>{children}{variant === 'primary' || variant === 'on-navy' ? <ArrowRight /> : null}</a>;
  }
  return (
    <button className={cls} onClick={onClick} type={type} disabled={disabled}>
      {children}{(variant === 'primary' || variant === 'on-navy') && type !== 'submit' ? <ArrowRight /> : null}
    </button>
  );
}

function ArrowRight() {
  return (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="M5 12h14"/><path d="m12 5 7 7-7 7"/>
    </svg>
  );
}

// ---- Footer --------------------------------------------------------------
function Footer() {
  return (
    <footer className="site-footer motif motif-arc on-navy">
      <div className="container-wide footer-inner">
        <div className="footer-brand">
          <span className="foot-wordmark">Behaving<span className="foot-dot">.co</span></span>
          <p className="foot-tagline">
            Find out why customers are leaving. Fix it.
          </p>
        </div>
        <div>
          <h4 className="footer-col-h">Site</h4>
          <ul className="footer-list">
            <li><a href="index.html">Home</a></li>
            <li><a href="services.html">Services</a></li>
            <li><a href="consulting.html">Consulting</a></li>
            <li><a href="about.html">About</a></li>
            <li><a href="contact.html">Contact</a></li>
          </ul>
        </div>
        <div>
          <h4 className="footer-col-h">Elsewhere</h4>
          <ul className="footer-list">
            <li><a href="https://cxdecoded.substack.com/">CX Decoded newsletter</a></li>
            <li><a href="https://linkedin.com/in/michaelhowlett">LinkedIn</a></li>
            <li><a href="mailto:michael@behaving.co">michael@behaving.co</a></li>
          </ul>
        </div>
        <div className="footer-legal">
          <span>ABN 92 908 136 631</span>
          <span>© 2026 Michael Howlett</span>
          <span>Made in Australia</span>
        </div>
      </div>
    </footer>
  );
}

// ---- Contact form (used on Home + Contact) ------------------------------
function ContactForm({ idPrefix = 'c', placeholder = "Churn is up. NPS is dropping. We just don't know where to start." }) {
  const [form, setForm] = useState({ name: '', email: '', need: '' });
  const [status, setStatus] = useState('idle');
  const [errors, setErrors] = useState({});
  const [submitError, setSubmitError] = useState('');

  const onChange = (e) => setForm({ ...form, [e.target.name]: e.target.value });
  const onSubmit = async (e) => {
    e.preventDefault();
    const errs = {};
    if (!form.name.trim()) errs.name = 'Your name helps me reply properly.';
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email)) errs.email = 'Needs to be a real email so I can reply.';
    if (!form.need.trim()) errs.need = 'A sentence is fine.';
    setErrors(errs);
    if (Object.keys(errs).length) return;
    setStatus('sending');
    setSubmitError('');
    try {
      const { supabaseUrl, supabaseAnonKey } = window.BEHAVING_CONFIG || {};
      if (!supabaseUrl || !supabaseAnonKey) throw new Error('Supabase not configured');
      const res = await fetch(`${supabaseUrl}/rest/v1/contact_submissions`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'apikey': supabaseAnonKey,
          'Authorization': `Bearer ${supabaseAnonKey}`,
          'Prefer': 'return=minimal',
        },
        body: JSON.stringify({ name: form.name.trim(), email: form.email.trim(), message: form.need.trim() }),
      });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      setStatus('sent');
    } catch (err) {
      setStatus('idle');
      setSubmitError('Something went wrong — please email me directly at michael@behaving.co.');
    }
  };

  if (status === 'sent') {
    return (
      <div className="form-success" role="status" aria-live="polite">
        <h3>Thanks{form.name.trim() ? `, ${form.name.trim().split(' ')[0]}` : ''}.</h3>
        <p>I read every enquiry myself and reply within a working day. If it is urgent, email me at <a href="mailto:michael@behaving.co">michael@behaving.co</a>.</p>
      </div>
    );
  }

  return (
    <form className="form" onSubmit={onSubmit} noValidate>
      <div className="field">
        <label htmlFor={`${idPrefix}-name`}>Your name</label>
        <input id={`${idPrefix}-name`} name="name" className={`in${errors.name ? ' in-error' : ''}`} value={form.name} onChange={onChange} autoComplete="name" />
        {errors.name && <div className="err">{errors.name}</div>}
      </div>
      <div className="field">
        <label htmlFor={`${idPrefix}-email`}>Email</label>
        <input id={`${idPrefix}-email`} name="email" type="email" className={`in${errors.email ? ' in-error' : ''}`} value={form.email} onChange={onChange} autoComplete="email" />
        {errors.email && <div className="err">{errors.email}</div>}
      </div>
      <div className="field">
        <label htmlFor={`${idPrefix}-need`}>What are you working on?</label>
        <textarea id={`${idPrefix}-need`} name="need" className={`in${errors.need ? ' in-error' : ''}`} rows="5" value={form.need} onChange={onChange} placeholder={placeholder} />
        {errors.need && <div className="err">{errors.need}</div>}
      </div>
      <div>
        <button type="submit" className="btn btn-primary" disabled={status === 'sending'}>
          {status === 'sending' ? 'Sending…' : 'Send enquiry'}
          {status !== 'sending' && <ArrowRight />}
        </button>
      </div>
      {submitError && <div className="err" role="alert">{submitError}</div>}
      <ul className="trust-strip" aria-hidden="true">
        <li><CheckIcon /> No pitch.</li>
        <li><CheckIcon /> Reply within 24 hours.</li>
        <li><CheckIcon /> If I cannot help, I will say so.</li>
      </ul>
    </form>
  );
}

function CheckIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <polyline points="20 6 9 17 4 12"/>
    </svg>
  );
}

// ---- Quote break ---------------------------------------------------------
function QuoteBreak({ quote, attrib }) {
  return (
    <section className="quote-break surface-navy motif motif-overlap on-navy" aria-label="Pull quote">
      <div className="container">
        <div className="qb-rule" aria-hidden="true"></div>
        <p className="qb-quote">{quote}</p>
        <p className="qb-attrib">{attrib}</p>
      </div>
    </section>
  );
}

// ---- Page wrapper --------------------------------------------------------
function Page({ children, current, screenLabel }) {
  const [theme, setTheme] = useTheme();
  return (
    <>
      <Header theme={theme} setTheme={setTheme} current={current} />
      <main data-screen-label={screenLabel}>{children}</main>
      <Footer />
    </>
  );
}

Object.assign(window, {
  Wordmark, Header, Button, ArrowRight, CheckIcon,
  Footer, ContactForm, QuoteBreak, Page, useTheme,
});
