// Nav + shared sections (services, about, writing, contact, footer)
const { useState: useStateS, useEffect: useEffectS, useRef: useRefS } = React;

// Inlines SVG logos (so CSS filter/invert works and buggy SVGs render)
// Falls back to <img> for non-SVG files (PNG etc.)
function ClientLogo({ src, alt }) {
  const ref = useRefS(null);
  const [svgText, setSvgText] = useStateS(null);
  const isSvg = src && src.toLowerCase().endsWith(".svg");

  useEffectS(() => {
    if (!isSvg) return;
    let cancelled = false;
    fetch(src + "?v=5").then(r => r.ok ? r.text() : "").then(t => {
      if (cancelled) return;
      let cleaned = t.replace(/<\?xml[^>]*\?>/g, "").replace(/<!DOCTYPE[^>]*>/gi, "").trim();
      // Force the root <svg> to have preserveAspectRatio and strip any width/height so CSS controls size
      cleaned = cleaned.replace(/<svg([^>]*)>/i, (m, attrs) => {
        // Capture width/height for possible viewBox derivation
        const wMatch = attrs.match(/\swidth\s*=\s*"([^"]+)"/i);
        const hMatch = attrs.match(/\sheight\s*=\s*"([^"]+)"/i);
        // Remove width/height so CSS controls sizing
        let a = attrs.replace(/\s(width|height)\s*=\s*"[^"]*"/gi, "");
        // Ensure viewBox — derive from width/height if absent
        if (!/viewBox/i.test(a)) {
          if (wMatch && hMatch) {
            const w = parseFloat(wMatch[1]);
            const h = parseFloat(hMatch[1]);
            if (w && h) a += ` viewBox="0 0 ${w} ${h}"`;
          }
        }
        if (!/preserveAspectRatio/i.test(a)) {
          a += ' preserveAspectRatio="xMidYMid meet"';
        }
        return `<svg${a}>`;
      });
      setSvgText(cleaned);
    }).catch(() => {});
    return () => { cancelled = true; };
  }, [src]);

  if (!isSvg) {
    return <img className="logo-img" src={src} alt={alt} loading="lazy" />;
  }
  if (!svgText) {
    return <span className="logo-img logo-img-loading" aria-label={alt} />;
  }
  return (
    <span
      className="logo-img logo-img-inline"
      role="img"
      aria-label={alt}
      ref={ref}
      dangerouslySetInnerHTML={{ __html: svgText }}
    />
  );
}

function Nav({ variant, onVariant }) {
  const [menuOpen, setMenuOpen] = useStateS(false);

  // Lock body scroll while the mobile menu is open
  useEffectS(() => {
    document.body.style.overflow = menuOpen ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [menuOpen]);

  const close = () => setMenuOpen(false);

  return (
    <nav className="coc-nav">
      <a className="coc-nav-brand" href="#top" onClick={close}>
        <span className="nav-brack">[</span>
        <span className="nav-name">crime<span className="nav-dot">.</span>of<span className="nav-dot">.</span>curiosity</span>
        <span className="nav-brack">]</span>
      </a>
      <div className="coc-nav-links">
        <a href="#services">services</a>
        <a href="#about">about</a>
        <a href="#clients">engagements</a>
        <a href="Blog.html">blog</a>
        <a href="#contact">contact</a>
      </div>
      <button
        className={`coc-nav-toggle ${menuOpen ? "is-open" : ""}`}
        aria-label={menuOpen ? "Close menu" : "Open menu"}
        aria-expanded={menuOpen}
        onClick={() => setMenuOpen(!menuOpen)}
      >
        <span className="nav-toggle-bar" />
        <span className="nav-toggle-bar" />
      </button>

      <div className={`coc-nav-overlay ${menuOpen ? "is-open" : ""}`} onClick={close}>
        <div className="nav-overlay-inner" onClick={(e) => e.stopPropagation()}>
          <a href="#services" onClick={close}><span className="nav-overlay-num">01</span> services</a>
          <a href="#about" onClick={close}><span className="nav-overlay-num">02</span> about</a>
          <a href="#clients" onClick={close}><span className="nav-overlay-num">03</span> engagements</a>
          <a href="Blog.html" onClick={close}><span className="nav-overlay-num">04</span> blog</a>
          <a href="#contact" onClick={close}><span className="nav-overlay-num">05</span> contact</a>
          <div className="nav-overlay-foot">
            <span className="nav-overlay-mark">my crime is that of curiosity</span>
          </div>
        </div>
      </div>
    </nav>
  );
}

function Services() {
  const [hover, setHover] = useStateS(null);
  return (
    <section id="services" className="sec-services">
      <div className="sec-head">
        <div className="sec-eyebrow">§ 02 / the practice</div>
        <h2 className="sec-title">Offensive security services we provide.</h2>
        <p className="sec-lede">
          We do not sell software. We do not sell dashboards. We sell the inconvenient findings that your board eventually thanks us for.
        </p>
      </div>

      <div className="svc-grid">
        {window.COC.SERVICES.map((s, i) => (
          <article
            key={s.id}
            className={`svc-card ${hover === i ? "is-hover" : ""}`}
            onMouseEnter={() => setHover(i)}
            onMouseLeave={() => setHover(null)}
          >
            <header className="svc-head">
              <span className="svc-id">[{s.id}]</span>
              <span className="svc-code">{s.code}</span>
            </header>
            <h3 className="svc-title">{s.title}</h3>
            <div className="svc-sub">{s.sub}</div>
            <p className="svc-body">{s.body}</p>
            <ul className="svc-bullets">
              {s.bullets.map((b) => (
                <li key={b}><span className="svc-tick">+</span>{b}</li>
              ))}
            </ul>
            <div className="svc-foot">
              <span className="svc-arrow">→</span>
              <span>scope an engagement</span>
            </div>
          </article>
        ))}
      </div>
    </section>
  );
}

function About() {
  const principles = [
    { k: "01", t: "The team member who scopes it, runs it.", d: "No offshore handoff. No junior bench. The person you speak with is testing your attack surface on day one and writes the report on the last." },
    { k: "02", t: "Proof, not theoretical impact.", d: "Every finding ships with a working, reproducible proof-of-concept and the exact path we took. If we can't demonstrate it, we don't report it." },
    { k: "03", t: "Targeted manual testing, not a vulnerability scan.", d: "We meticulously analyze the in-scope attack surface to find impactful issues. No repackaged Nessus scans here." },
    { k: "04", t: "Human-in-the-loop AI.", d: "Only if you want it. We pair operator-directed AI with manual testing to cover your attack surface more thoroughly and efficiently — every result validated by the person running the engagement, never acted on unsupervised." },
  ];
  return (
    <section id="about" className="sec-aboutus">
      <div className="abt-head">
        <div className="sec-eyebrow">§ 03 / who we are</div>
        <h2 className="sec-title">Curiosity, under contract.</h2>
      </div>

      <div className="abt-grid">
        <div className="abt-prose">
          <p>
            Crime of Curiosity is a small team of offensive security practitioners. We have decades of experience delivering security assessments: from full-scope penetration tests and red team engagements to social engineering, cloud, and source-assisted application review. We stay on the cutting edge of novel attacks and emerging techniques, and we've delivered results for Fortune 100, technology, healthcare, and government organizations.
          </p>
          <p>
            Between us we hold certifications like the OSCP and CISA, rank among the top researchers on major bug-bounty platforms, have published CVEs and vulnerability advisories, and have presented our research at industry summits and conferences.
          </p>
        </div>

        <div className="abt-principles">
          <div className="abt-principles-label">how we operate</div>
          {principles.map((p) => (
            <div key={p.k} className="abt-principle">
              <span className="abt-principle-k">{p.k}</span>
              <div className="abt-principle-body">
                <div className="abt-principle-t">{p.t}</div>
                <div className="abt-principle-d">{p.d}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Clients() {
  return (
    <section id="clients" className="sec-about">
      <div className="about-layout">
        <div className="sec-head about-intro">
          <div className="sec-eyebrow">§ 04 / engagements</div>
          <h2 className="sec-title">
            A few of the organizations we've worked with.
          </h2>
          <p className="sec-lede">
            Our work spans global banks and insurers, defense primes, federal agencies, healthcare and pharma, household consumer brands, and the high-growth software companies behind everyday infrastructure.
          </p>
        </div>

        <div className="about-rosters">
          <div className="roster-section">
            <div className="roster-section-head">
              <div className="roster-section-label">private sector</div>
            </div>
            <div className="logo-wall">
              {window.COC.CLIENTS_PRIVATE.map((c) => (
                <div key={c.name} className={`logo-tile ${c.logo ? "has-logo" : ""}`} title={c.name} aria-label={c.name}>
                  {c.logo
                    ? <ClientLogo src={c.logo} alt={c.name} />
                    : <span className="logo-mono">{c.mono}</span>}
                  <span className="logo-name">{c.name}</span>
                </div>
              ))}
            </div>
          </div>

          <div className="roster-section">
            <div className="roster-section-head">
              <div className="roster-section-label">government</div>
            </div>
            <div className="logo-wall logo-wall-gov">
              {window.COC.CLIENTS_GOV.map((c) => (
                <div key={c.name} className={`logo-tile logo-tile-gov ${c.logo ? "has-logo" : ""}`} title={c.name} aria-label={c.name}>
                  {c.logo
                    ? <ClientLogo src={c.logo} alt={c.name} />
                    : <span className="logo-mono">{c.mono}</span>}
                  <span className="logo-name">{c.name}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function Writing() {
  return (
    <section id="writing" className="sec-writing">
      <div className="sec-head">
        <div className="sec-eyebrow">§ 05 / blog</div>
        <h2 className="sec-title">Research, advisories, and stories from the field.</h2>
      </div>
      <div className="write-list">
        {window.COC.WRITING.slice(0, 4).map((w, i) => (
          <a key={i} className="write-row" href="Blog.html">
            <span className="write-date">{w.date}</span>
            <span className={`write-tag write-tag-${w.tag.toLowerCase().replace(/\s+/g,"-")}`}>{w.tag}</span>
            <span className="write-title">{w.title}</span>
            <span className="write-read">{w.read}</span>
            <span className="write-arrow">→</span>
          </a>
        ))}
      </div>
      <a className="write-all" href="Blog.html">
        read the full blog <span className="write-all-arrow">→</span>
      </a>
    </section>
  );
}

function Contact() {
  const [status, setStatus] = useStateS("idle"); // idle | sending | sent | error

  const onSubmit = async (e) => {
    e.preventDefault();
    if (status === "sending" || status === "sent") return;
    const form = e.target;
    const data = new FormData(form);
    setStatus("sending");
    try {
      const res = await fetch("https://api.web3forms.com/submit", {
        method: "POST",
        headers: { Accept: "application/json" },
        body: data,
      });
      const json = await res.json();
      if (json.success) setStatus("sent");
      else setStatus("error");
    } catch (err) {
      setStatus("error");
    }
  };

  const btnLabel =
    status === "sending" ? "◌ transmitting…" :
    status === "sent" ? "◉ transmitted" :
    status === "error" ? "✕ failed — retry" :
    "▸ transmit";

  return (
    <section id="contact" className="sec-contact">
      <div className="sec-head">
        <div className="sec-eyebrow">§ 06 / initiate contact</div>
        <h2 className="sec-title">
          Tell us what you're worried about.<br />
          We'll tell you if we can help.
        </h2>
        <p className="sec-lede">
          No sales engineers. No discovery call. The first person you email is the person who runs the engagement.
        </p>
      </div>

      <div className="contact-grid">
        <form className="contact-form" onSubmit={onSubmit}>
          <input type="hidden" name="access_key" value="657d76f2-3087-4d8d-9556-458f7d593b53" />
          <input type="hidden" name="subject" value="New inquiry — crimeofcuriosity.com" />
          <input type="hidden" name="from_name" value="Crime of Curiosity — contact form" />
          {/* honeypot: bots fill this, humans never see it */}
          <input type="checkbox" name="botcheck" tabIndex="-1" autoComplete="off" style={{ display: "none" }} />

          <label className="cf-row">
            <span className="cf-k">&gt; name</span>
            <input type="text" name="name" required placeholder="how should we address you" />
          </label>
          <label className="cf-row">
            <span className="cf-k">&gt; organization</span>
            <input type="text" name="organization" placeholder="company, division, or 'personal'" />
          </label>
          <label className="cf-row">
            <span className="cf-k">&gt; email</span>
            <input type="email" name="email" required placeholder="however we should reach you" />
          </label>
          <label className="cf-row cf-row-area">
            <span className="cf-k">&gt; brief</span>
            <textarea name="message" rows="5" required placeholder="what are you trying to learn? what keeps you up?" />
          </label>

          <div className="cf-foot">
            <button type="submit" className={`cf-btn cf-btn-${status}`} disabled={status === "sending" || status === "sent"}>
              {btnLabel}
            </button>
            {status === "sent" && (
              <span className="cf-msg cf-msg-ok">message received — we'll be in touch.</span>
            )}
            {status === "error" && (
              <span className="cf-msg cf-msg-err">something broke. email hello@crimeofcuriosity.com directly.</span>
            )}
          </div>
        </form>

        <aside className="contact-aside">
          <div className="ca-block">
            <div className="ca-k">direct</div>
            <div className="ca-v">hello@crimeofcuriosity.com</div>
          </div>
          <div className="ca-block">
            <div className="ca-k">disclosures</div>
            <div className="ca-v">security@crimeofcuriosity.com</div>
          </div>
          <div className="ca-block">
            <div className="ca-k">careers</div>
            <div className="ca-v">careers@crimeofcuriosity.com</div>
          </div>
        </aside>
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer className="coc-footer">
      <div className="foot-l">
        <div className="foot-brand">crime<span className="foot-dot">.</span>of<span className="foot-dot">.</span>curiosity</div>
        <div className="foot-tag">offensive security · since 2015</div>
      </div>
      <div className="foot-c">
        <div className="foot-line">— my crime is that of curiosity —</div>
      </div>
      <div className="foot-r">
        <a className="foot-mail" href="mailto:hello@crimeofcuriosity.com">hello@crimeofcuriosity.com</a>
        <div className="foot-legal">© 2026 crime of curiosity · all rights reserved</div>
      </div>
    </footer>
  );
}

Object.assign(window, { Nav, Services, About, Clients, Writing, Contact, Footer });
