/* global React */
const { useState, useEffect, useRef, useMemo } = React;

/* ============================================================
   Logo, uses brand PNG with full "People Cake" wordmark
   ============================================================ */
function Logo({ height = 40, src = "assets/logo.png" }) {
  return (
    <img
      src={src}
      alt="People Cake"
      style={{
        height,
        width: "auto",
        display: "block",
        userSelect: "none"
      }}
      draggable="false" />);


}

/* ============================================================
   Icons
   ============================================================ */
const IconArrow = ({ size = 16 }) =>
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
    <line x1="4" y1="12" x2="20" y2="12" />
    <polyline points="14 6 20 12 14 18" />
  </svg>;

const IconCheck = ({ size = 16 }) =>
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <polyline points="20 6 9 17 4 12" />
  </svg>;

const IconLinkedIn = ({ size = 16 }) =>
<svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor">
    <path d="M19 3a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14zM8.34 18.34V9.67H5.66v8.67h2.68zM7 8.51a1.56 1.56 0 1 0 0-3.11 1.56 1.56 0 0 0 0 3.11zm11.34 9.83v-4.95c0-2.55-1.36-3.74-3.18-3.74-1.47 0-2.13.81-2.5 1.38v-1.19h-2.68c.04.77 0 8.5 0 8.5h2.68v-4.84c0-.24.02-.48.09-.65.19-.48.63-.98 1.36-.98.96 0 1.34.73 1.34 1.8v4.67h2.69z" />
  </svg>;

const IconEmail = ({ size = 16 }) =>
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
    <rect x="3" y="5" width="18" height="14" rx="2" />
    <polyline points="3 7 12 13 21 7" />
  </svg>;


/* Big background gear ornament */
function BgGear({ style = {}, size = 600, opacity = 0.04 }) {
  return (
    <svg
      viewBox="0 0 200 200" width={size} height={size}
      style={{ position: "absolute", opacity, pointerEvents: "none", ...style }}
      aria-hidden="true">
      
      <g fill="none" stroke="currentColor" strokeWidth="0.6">
        <circle cx="100" cy="100" r="60" />
        <circle cx="100" cy="100" r="40" />
        {[...Array(16)].map((_, i) => {
          const a = i / 16 * Math.PI * 2;
          const x1 = 100 + Math.cos(a) * 60;
          const y1 = 100 + Math.sin(a) * 60;
          const x2 = 100 + Math.cos(a) * 72;
          const y2 = 100 + Math.sin(a) * 72;
          return <line key={i} x1={x1} y1={y1} x2={x2} y2={y2} />;
        })}
      </g>
    </svg>);

}

/* ============================================================
   Nav
   ============================================================ */
function Nav({ route, navigate, onCTA }) {
  const [scrolled, setScrolled] = useState(false);
  const [drawerOpen, setDrawerOpen] = useState(false);

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

  // Nav is always dark/black across all pages and scroll states.
  const navClass = "nav nav--dark-solid";

  const links = [
  { id: "home", label: "Home" },
  { id: "about", label: "About" },
  { id: "consultancy", label: "HR Consultancy" },
  { id: "coaching", label: "Career Coaching" },
  { id: "partners", label: "Partners" }];


  const go = (id) => {navigate(id);setDrawerOpen(false);};

  return (
    <React.Fragment>
      <header className={navClass}>
        <div className="nav__inner">
          <div className="nav__logo" onClick={() => go("home")} style={{ cursor: "pointer" }}>
            <Logo height={128} src="assets/logo-large.png" />
          </div>
          <nav className="nav__links">
            {links.map((l) =>
            <a key={l.id}
            className={"nav__link" + (route === l.id ? " nav__link--active" : "")}
            onClick={() => go(l.id)}>
                {l.label}
              </a>
            )}
          </nav>
          <button className="btn btn--primary nav__cta" onClick={onCTA}>Work With Me</button>
          <button className="nav__hamburger" onClick={() => setDrawerOpen(true)} aria-label="Open menu">
            <span /><span /><span />
          </button>
        </div>
      </header>

      <div className={"drawer" + (drawerOpen ? " drawer--open" : "")}>
        <button className="drawer__close" onClick={() => setDrawerOpen(false)} aria-label="Close menu">✕</button>
        <div className="nav__logo" style={{ marginBottom: 24 }}>
          <Logo height={112} />
        </div>
        <div className="drawer__links">
          {links.map((l) =>
          <a key={l.id} className="drawer__link" onClick={() => go(l.id)}>{l.label}</a>
          )}
        </div>
        <button className="btn btn--primary" style={{ marginTop: 32 }} onClick={() => {onCTA();setDrawerOpen(false);}}>
          Work With Me
        </button>
      </div>
    </React.Fragment>);

}

/* ============================================================
   Footer
   ============================================================ */
function Footer({ navigate, onCTA }) {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer__grid">
          <div style={{ textAlign: "left" }}>
            <div className="footer__heading">Navigate</div>
            <div className="footer__nav">
              <a onClick={() => navigate("home")}>Home</a>
              <a onClick={() => navigate("about")}>About</a>
              <a onClick={() => navigate("consultancy")}>HR Consultancy</a>
              <a onClick={() => navigate("coaching")}>Career Coaching</a>
              <a onClick={() => navigate("programmes")}>Programmes &amp; Membership</a>
              <a onClick={() => navigate("partners")}>Partners</a>
            </div>
          </div>

          <div>
            <div className="footer__heading">Get started</div>
            <div className="footer__nav" style={{ marginBottom: 24 }}>
              <a onClick={() => navigate("diagnostic")}>Team Diagnostic Tool</a>
              <a onClick={() => navigate("career-health-check")}>Career Health Check</a>
              <a onClick={onCTA}>Book a conversation</a>
              <a href="mailto:sarah@peoplecake.com">sarah@peoplecake.com</a>
            </div>
            <button className="btn btn--primary" onClick={onCTA}>Work With Me</button>
          </div>

          <div>
            <div className="nav__logo">
              <Logo height={144} src="assets/logo-mark.png" />
            </div>
            <p className="footer__mission">
              Strategic HR depth for scaling businesses and ambitious HR leaders.
            </p>
            <div className="footer__socials">
              <a href="https://www.linkedin.com/company/people-cake-consulting-ltd/" target="_blank" rel="noopener" aria-label="LinkedIn">
                <IconLinkedIn size={16} />
              </a>
              <a href="mailto:sarah@peoplecake.com" aria-label="Email">
                <IconEmail size={16} />
              </a>
            </div>
          </div>
        </div>
        <div className="footer__bottom">
          <span>© 2026 People Cake · Strategic HR for scaling businesses</span>
          <span style={{ display: "flex", gap: 24 }}>
            <a style={{ cursor: "pointer", opacity: 0.7 }} onClick={() => navigate("privacy")}>Privacy Policy</a>
            <a style={{ cursor: "pointer", opacity: 0.7 }} onClick={() => navigate("privacy")}>Cookies</a>
          </span>
        </div>
      </div>
    </footer>);

}

/* ============================================================
   Testimonial
   ============================================================ */
function Testimonial({ quote, name, role }) {
  return (
    <div className="testimonial">
      <span className="testimonial__mark testimonial__mark--open" aria-hidden="true">“</span>
      <p className="testimonial__quote">
        {quote}
        <span className="testimonial__mark testimonial__mark--close" aria-hidden="true">”</span>
      </p>
      <div className="testimonial__attr">
        {name ?
        <React.Fragment>
            <span className="testimonial__name">{name}</span>{role && <span> · {role}</span>}
          </React.Fragment> :
        <span style={{ fontStyle: "italic" }}>{role}</span>}
      </div>
    </div>);

}

/* ============================================================
   Contact modal
   ============================================================ */
function ContactModal({ open, onClose, accent = "purple" }) {
  const [submitted, setSubmitted] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");
  const [form, setForm] = useState({ name: "", email: "", company: "", interest: "consultancy", message: "" });

  useEffect(() => {
    if (open) {
      setSubmitted(false);
      setSubmitting(false);
      setError("");
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "";
    }
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  const interestLabel = {
    consultancy: "HR Consultancy, for my business",
    coaching: "Career Coaching, for me",
    diagnostic: "Team Diagnostic tool",
    partner: "Partnership opportunity"
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setSubmitting(true);
    setError("");
    try {
      const payload = {
        access_key: "185359e5-9b58-4947-b399-87d2906c57b6",
        subject: `New People Cake enquiry from ${form.name} (${interestLabel[form.interest] || form.interest})`,
        from_name: "People Cake website",
        name: form.name,
        email: form.email,
        company: form.company,
        interest: interestLabel[form.interest] || form.interest,
        message: form.message,
        replyto: form.email,
        botcheck: ""
      };
      const res = await fetch("https://api.web3forms.com/submit", {
        method: "POST",
        headers: { "Content-Type": "application/json", "Accept": "application/json" },
        body: JSON.stringify(payload)
      });
      const data = await res.json();
      if (data.success) {
        setSubmitted(true);
      } else {
        setError(data.message || "Something went wrong. Please email sarah@peoplecake.com directly.");
      }
    } catch (err) {
      setError("Couldn't reach the server. Please email sarah@peoplecake.com directly.");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className={"modal-overlay" + (open ? " modal-overlay--open" : "")} onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <button className="modal__close" onClick={onClose} aria-label="Close">✕</button>
        {!submitted ?
        <React.Fragment>
            <div className="t-label eyebrow eyebrow--purple">Let's talk</div>
            <h2 className="t-h2" style={{ marginBottom: 16 }}>Start a conversation.</h2>
            <p className="text-mid" style={{ marginBottom: 32 }}>
              A short message, a quick reply. No lengthy proposals, no sales calls, just a conversation to see if there's a fit.
            </p>
            <form className="form" onSubmit={handleSubmit}>
              <div className="form__field">
                <label className="form__label">Your name</label>
                <input className="form__input" required value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
              </div>
              <div className="form__field">
                <label className="form__label">Email</label>
                <input className="form__input" type="email" required value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} />
              </div>
              <div className="form__field">
                <label className="form__label">Company <span className="text-mid" style={{ fontWeight: 400 }}>(optional)</span></label>
                <input className="form__input" value={form.company} onChange={(e) => setForm({ ...form, company: e.target.value })} />
              </div>
              <div className="form__field">
                <label className="form__label">I'm interested in</label>
                <select className="form__select" value={form.interest} onChange={(e) => setForm({ ...form, interest: e.target.value })}>
                  <option value="consultancy">HR Consultancy, for my business</option>
                  <option value="coaching">Career Coaching, for me</option>
                  <option value="diagnostic">Team Diagnostic tool</option>
                  <option value="partner">Partnership opportunity</option>
                </select>
              </div>
              <div className="form__field">
                <label className="form__label">Anything specific you'd like to share?</label>
                <textarea className="form__input" rows="3" value={form.message} onChange={(e) => setForm({ ...form, message: e.target.value })} />
              </div>
              <button type="submit" disabled={submitting} className={"btn " + (accent === "violet" ? "btn--coaching" : "btn--primary") + " btn--lg"}>
                {submitting ? "Sending\u2026" : <React.Fragment>Send message <IconArrow /></React.Fragment>}
              </button>
              {error ? (
                <p className="t-small" style={{ color: "#c2410c", textAlign: "center", marginTop: 4 }}>{error}</p>
              ) : null}
            </form>
          </React.Fragment> :

        <div style={{ textAlign: "center", padding: "32px 0" }}>
            <div style={{
            width: 64, height: 64, borderRadius: "50%",
            background: "var(--color-yellow)", color: "var(--color-black)",
            display: "inline-flex", alignItems: "center", justifyContent: "center",
            marginBottom: 24
          }}>
              <IconCheck size={28} />
            </div>
            <h2 className="t-h2" style={{ marginBottom: 16 }}>Message received.</h2>
            <p className="text-mid" style={{ marginBottom: 32 }}>
              Thanks {form.name || "for getting in touch"}, I'll be in touch shortly.
            </p>
            <button className="btn btn--ghost" onClick={onClose}>Close</button>
          </div>
        }
      </div>
    </div>);

}

/* ============================================================
   Cred bar
   ============================================================ */
function CredBar({ items }) {
  return (
    <div className="cred-bar">
      {items.map((item, i) =>
      <div key={i} className="cred-bar__item">
          <span className="cred-bar__bullet" aria-hidden="true" />
          <span>{item}</span>
        </div>
      )}
    </div>);

}

/* ============================================================
   Export
   ============================================================ */
Object.assign(window, {
  Logo, BgGear,
  IconArrow, IconCheck, IconLinkedIn, IconEmail,
  Nav, Footer, Testimonial, ContactModal, CredBar
});