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

const Icon = ({ name, size = 20, stroke = 1.6 }) => {
  const props = { width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: stroke, strokeLinecap: "round", strokeLinejoin: "round" };
  const paths = {
    arrow: <><path d="M7 17 17 7" /><path d="M8 7h9v9" /></>,
    download: <><path d="M12 3v12" /><path d="m7 10 5 5 5-5" /><path d="M5 21h14" /></>,
  };
  return <svg {...props}>{paths[name]}</svg>;
};

const Brand = () => (
  <a href="#" className="brand">
    <img src="assets/logo.png" alt="" />
    <span className="brand-name"><span>beyond</span><span>recon</span></span>
  </a>
);

const Nav = () => {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <nav className={"nav " + (scrolled ? "scrolled" : "")}>
      <div className="nav-inner">
        <Brand />
        <div className="nav-links">
          <a href="#services">Services</a>
          <a href="#about">About</a>
          <a href="#blog">Blog</a>
          <a href="#contact">Contact</a>
        </div>
      </div>
    </nav>
  );
};

/* TERMINAL */
const TERMINAL_SCRIPT = [
  { type: "cmd", text: "recon --target acme-corp.io --scope external" },
  { type: "out", text: "[*] Initializing reconnaissance against acme-corp.io" },
  { type: "out", text: "[*] DNS enumeration · subdomain bruteforce · cert mining", delay: 400 },
  { type: "ok", text: "[+] 247 subdomains · 41 IPs · 12 ASNs discovered", delay: 600 },
  { type: "out", text: "[*] Service fingerprinting on 247 hosts...", delay: 300 },
  { type: "warn", text: "[!] Port 8080 → Jenkins 2.289 (CVE-2021-2114)", delay: 500 },
  { type: "warn", text: "[!] Port 6379 → Redis 5.0.3 · NO AUTH · publicly exposed", delay: 500 },
  { type: "crit", text: "[CRIT] api-staging.acme-corp.io · default credentials", delay: 600 },
  { type: "crit", text: "[CRIT] SSRF → AWS metadata · IAM role: prod-deploy-svc", delay: 700 },
  { type: "crit", text: "[CRIT] s3://acme-customer-data · 4.2M records · world-readable", delay: 800 },
  { type: "ok", text: "[+] Engagement complete · 14 findings · report drafted", delay: 600 },
  { type: "dim", text: "──────────────────────────────────────────────────" },
  { type: "dim", text: "  CRITICAL  3   HIGH  5   MEDIUM  4   LOW  2" },
];

const Terminal = () => {
  const [lines, setLines] = useState([]);
  const ref = useRef();

  useEffect(() => {
    let cancelled = false;
    let i = 0;
    let buf = [];
    const loop = async () => {
      if (cancelled) return;
      if (i >= TERMINAL_SCRIPT.length) {
        await new Promise(r => setTimeout(r, 4000));
        if (cancelled) return;
        i = 0; buf = []; setLines([]);
        loop();
        return;
      }
      const item = TERMINAL_SCRIPT[i];
      if (item.type === "cmd") {
        let typed = "";
        setLines([...buf, { type: "cmd-typing", text: "" }]);
        for (let c = 0; c < item.text.length; c++) {
          if (cancelled) return;
          typed += item.text[c];
          setLines([...buf, { type: "cmd-typing", text: typed }]);
          await new Promise(r => setTimeout(r, 18 + Math.random() * 30));
        }
        buf = [...buf, { type: "cmd", text: item.text }];
        setLines(buf);
        await new Promise(r => setTimeout(r, 350));
      } else {
        buf = [...buf, item];
        setLines(buf);
        await new Promise(r => setTimeout(r, item.delay || 250));
      }
      i++;
      loop();
    };
    loop();
    return () => { cancelled = true; };
  }, []);

  useEffect(() => {
    if (ref.current) ref.current.scrollTop = ref.current.scrollHeight;
  }, [lines]);

  const renderLine = (l, idx) => {
    if (l.type === "cmd" || l.type === "cmd-typing") {
      return (
        <span key={idx} className="term-line">
          <span className="term-user">recon@beyondrecon</span>
          <span className="term-out">:</span>
          <span className="term-path">~/engagements/acme</span>
          <span className="term-out">$ </span>
          <span className="term-prompt">{l.text}</span>
          {l.type === "cmd-typing" && <span className="term-cursor" />}
        </span>
      );
    }
    const cls = { ok: "term-ok", warn: "term-warn", crit: "term-crit", out: "term-out", dim: "term-dim" }[l.type] || "term-out";
    return <span key={idx} className={"term-line " + cls}>{l.text}</span>;
  };

  return (
    <div className="terminal">
      <div className="terminal-bar">
        <div className="terminal-dots"><span /><span /><span /></div>
        <div className="terminal-title"><b>recon-cli</b> · acme-corp.io · external</div>
      </div>
      <div className="terminal-body" ref={ref}>
        {lines.map(renderLine)}
      </div>
    </div>
  );
};

const Hero = () => (
  <section className="hero">
    <div className="hero-grid-bg" />
    <div className="hero-glow" />
    <div className="wrap hero-inner">
      <div className="hero-left">
        <div className="eyebrow">Founded by bug bounty hunters</div>
        <h1>
          We dig deeper<br />
          <span className="highlight">than</span> the checklist.
        </h1>
        <p className="sub">
          Pentesting from people who hunt bugs for a living. We respect your scope. and inside it, we don't stop at the first finding. We keep going until we've actually understood what an attacker could do.
        </p>
        <div className="hero-cta">
          <a className="btn btn-primary" href="mailto:hello@beyondrecon.com?subject=Engagement%20enquiry">Talk to us <Icon name="arrow" size={16} /></a>
          <a className="btn btn-ghost btn-mono" href="#method">See how we work</a>
        </div>
      </div>
      <div className="hero-right">
        <Terminal />
      </div>
    </div>
  </section>
);

const MARQUEE_ITEMS = ["Google", "Ubiquiti", "SoundCloud", "Private programs", "HackerOne", "Bugcrowd", "Fortune 500s", "+ undisclosed"];
const Marquee = () => (
  <section className="marquee">
    <h2 className="marquee-eyebrow">
      Our hackers have been<br /><span className="accent">acknowledged by</span>
    </h2>
    <div className="marquee-track">
      {[...MARQUEE_ITEMS, ...MARQUEE_ITEMS, ...MARQUEE_ITEMS].map((t, i) => (
        <div key={i} className="marquee-item"><span className="dot" />{t}</div>
      ))}
    </div>
  </section>
);

const SERVICES = [
  { num: "01", name: "Web Apps & APIs", desc: "The bread and butter. Auth flows, IDOR, business logic abuse, GraphQL, OAuth chains. The bugs scanners miss.", tags: ["OWASP", "GraphQL", "OAuth"] },
  { num: "02", name: "Network & Infra", desc: "External perimeter, internal pivots, AD attack paths. We assume the phish landed and keep going from there.", tags: ["AD", "Pivot", "Lateral"] },
  { num: "03", name: "Cloud", desc: "AWS, Azure, GCP. IAM weirdness, exposed metadata, escape paths from compromised workloads.", tags: ["IAM", "K8s", "S3"] },
  { num: "04", name: "Mobile", desc: "iOS and Android. Binary analysis, runtime instrumentation, pinning bypass, the data your app leaks at rest.", tags: ["iOS", "Android", "Frida"] },
  { num: "05", name: "Red Team", desc: "Pick an objective. We'll get there. Phish, foothold, persistence, exfil. the whole chain, end to end.", tags: ["MITRE", "C2", "Phish"] },
  { num: "06", name: "Code Review", desc: "Manual review by hackers who've written the same bugs. We find what SAST and tired interns can't.", tags: ["Audit", "SDLC", "Source"] },
];

const Services = () => (
  <section id="services" className="section section-divider">
    <div className="wrap">
      <div className="sec-head">
        <div className="eyebrow">What we do</div>
        <h2>An idea of<br /><span className="accent">what we hack.</span></h2>
        <p className="desc">Not a service catalog. If your stack isn't here, ask anyway. we've probably broken it before.</p>
      </div>
      <div className="services">
        {SERVICES.map(s => (
          <div className="service" key={s.num}>
            <div className="service-arrow"><Icon name="arrow" size={18} /></div>
            <div className="service-num">{s.num} / 06</div>
            <h3>{s.name}</h3>
            <p>{s.desc}</p>
            <div className="service-tags">
              {s.tags.map(t => <span key={t} className="service-tag">{t}</span>)}
            </div>
          </div>
        ))}
      </div>
    </div>
  </section>
);

const METHOD_STEPS = [
  { num: "01", name: "You message us", time: "Same day", short: "No sales calls. No forms.", desc: "You email or DM. We reply. usually within hours, from a real hacker, not a sales engineer. Tell us what you have, what you're worried about, and we'll tell you straight whether we're a fit.", checks: ["You talk to a hacker on day one", "No qualifying calls, no funnels", "Straight answer in 24 hours or less", "NDA in your hands by tomorrow"] },
  { num: "02", name: "We scope it", time: "30 minutes", short: "One call. That's the intake.", desc: "Half an hour on a call. We agree what's in scope, what's explicitly out, and what 'done' looks like. Then we send a fixed quote and a start date. usually next week.", checks: ["One thirty-minute call", "Fixed price, no surprise invoices", "Start date within 7–10 days", "Plain-English statement of work"] },
  { num: "03", name: "We hack", time: "As long as it takes", short: "Inside scope, all the way down", desc: "Manual testing, bug-bounty instincts, custom tooling. Your scope is the perimeter. and inside it, we go deeper than a checklist would. We don't call it done at the first finding; we keep digging until we understand what a real attacker could do.", checks: ["Strict respect for agreed scope", "Manual testing, not just scanners", "Daily updates on a shared channel", "We chase every lead inside the line"] },
  { num: "04", name: "You get the report", time: "A few days after", short: "Findings your devs can ship", desc: "Every finding has a working PoC, the exact request, business impact, and a fix you can apply. Markdown, PDF, or straight into your Jira. No 80-page filler.", checks: ["Working PoC for every critical", "Engineering-ready fix steps", "Live readout call with your team", "Markdown · PDF · Jira import"] },
  { num: "05", name: "We retest free", time: "Anytime within 60 days", short: "Until it's actually fixed", desc: "You patch, we re-test. No clock, no extra invoice. We re-issue the report clean once it's closed. for your auditors, your board, or your own peace of mind.", checks: ["Free retest within 60 days", "Re-issued clean report on close", "Attestation letter on request", "Always one DM away after"] },
];

const Methodology = () => {
  const [active, setActive] = useState(0);
  const cur = METHOD_STEPS[active];
  return (
    <section id="method" className="section section-divider">
      <div className="wrap">
        <div className="sec-head">
          <div className="eyebrow">How we work</div>
          <h2>Zero bureaucracy.<br /><span className="accent">Just hacking.</span></h2>
          <p className="desc">Five steps from first DM to fixed bug. Hover any one to see what happens inside.</p>
        </div>
        <div className="method">
          <div className="method-steps">
            {METHOD_STEPS.map((s, i) => (
              <div
                key={s.num}
                className={"method-step " + (i === active ? "active" : "")}
                onMouseEnter={() => setActive(i)}
                onClick={() => setActive(i)}
              >
                <div className="method-num">{s.num}</div>
                <div>
                  <div className="method-step-name">{s.name}</div>
                  <div className="method-step-desc">{s.short}</div>
                </div>
                <div className="method-step-time">{s.time}</div>
              </div>
            ))}
          </div>
          <div className="method-detail">
            <div className="method-detail-num">PHASE {cur.num} · {cur.time}</div>
            <h3>{cur.name}</h3>
            <p>{cur.desc}</p>
            <ul className="method-checklist">
              {cur.checks.map(c => <li key={c}>{c}</li>)}
            </ul>
          </div>
        </div>
      </div>
    </section>
  );
};

const Stats = () => (
  <section className="stats-section section">
    <div className="wrap">
      <div className="stats">
        {[
          { num: <><span className="accent">0</span></>, lbl: "Sales engineers", desc: "You talk to a hacker on day one. Always." },
          { num: <>24<span className="accent">h</span></>, lbl: "Reply window", desc: "From first email to a real human answering. same day, usually." },
          { num: <><span className="accent">100</span>%</>, lbl: "Manual testing", desc: "Scanners are a starting point, not a deliverable." },
          { num: <>60<span className="accent">d</span></>, lbl: "Free retest", desc: "You patch, we verify. No clock, no extra invoice." },
        ].map((s, i) => (
          <div className="stat" key={i}>
            <div className="stat-lbl">{s.lbl}</div>
            <div className="stat-num">{s.num}</div>
            <div className="stat-desc">{s.desc}</div>
          </div>
        ))}
      </div>
    </div>
  </section>
);

const ContactForm = () => {
  const [status, setStatus] = useState("idle"); // idle | sending | sent | error
  const [errorMsg, setErrorMsg] = useState("");
  const formRef = useRef();

  const onSubmit = async (e) => {
    e.preventDefault();
    setStatus("sending");
    setErrorMsg("");
    try {
      const data = new FormData(formRef.current);
      const res = await fetch("https://api.web3forms.com/submit", { method: "POST", body: data });
      const json = await res.json().catch(() => ({}));
      if (res.ok && json.success !== false) {
        setStatus("sent");
        formRef.current.reset();
      } else {
        setStatus("error");
        setErrorMsg(json.message || "Something went wrong. Please email us directly.");
      }
    } catch (err) {
      setStatus("error");
      setErrorMsg("Network error. Please email us directly at hello@beyondrecon.com.");
    }
  };

  if (status === "sent") {
    return (
      <div className="cf-banner cf-banner-success">
        <div className="cf-banner-icon">✓</div>
        <h3>Message sent.</h3>
        <p>A hacker will read this and reply within 24 hours, usually sooner.</p>
        <button type="button" className="cf-banner-link" onClick={() => setStatus("idle")}>Send another</button>
      </div>
    );
  }

  return (
    <form ref={formRef} className="contact-form" onSubmit={onSubmit}>
      <input type="hidden" name="access_key" value="08091ec0-5143-4e5c-9b48-d2a69fa304e9" />
      <input type="hidden" name="subject" value="New BeyondRecon enquiry" />
      <input type="hidden" name="from_name" value="BeyondRecon contact form" />
      <input type="checkbox" name="botcheck" style={{ display: "none" }} tabIndex={-1} autoComplete="off" />
      <div className="form-row">
        <input className="cf-input" type="text" name="full_name" placeholder="Full Name" required />
        <input className="cf-input" type="email" name="email" placeholder="Email Address" required />
      </div>
      <div className="form-row">
        <input className="cf-input" type="tel" name="phone" placeholder="Phone Number" />
        <input className="cf-input" type="text" name="company" placeholder="Company Name" />
      </div>
      <textarea className="cf-input cf-textarea" name="message" rows={5} placeholder="Let us know how we can help you..." required />
      <p className="cf-disclaimer">
        By submitting this contact form, you agree that the details provided will be used to contact you regarding your enquiry.
      </p>
      {status === "error" && <div className="cf-error">{errorMsg}</div>}
      <button type="submit" className="cf-submit" disabled={status === "sending"}>
        {status === "sending" ? "Sending..." : "Get in touch"}
      </button>
    </form>
  );
};

const CTA = () => (
  <section id="contact" className="section cta-section">
    <div className="wrap">
      <div className="cta-card">
        <div className="corner-ticks"><span /><span /><span /><span /></div>
        <div className="eyebrow">Open for new clients</div>
        <h2>Tell us what you need.<br /><span className="accent">We'll reply today.</span></h2>
        <p>A real hacker reads every message. Give us the shape of the engagement and we'll tell you straight whether we're a fit.</p>
        <ContactForm />
      </div>
    </div>
  </section>
);

const SOCIALS = [
  {
    name: "LinkedIn",
    href: "https://www.linkedin.com/company/beyondrecon",
    svg: <><rect x="2" y="2" width="20" height="20" rx="3" /><path d="M7 10v7" /><circle cx="7" cy="7" r="0.5" /><path d="M11 17v-4a3 3 0 0 1 6 0v4" /><path d="M11 10v7" /></>,
  },
  {
    name: "GitHub",
    href: "https://github.com/beyondrecon",
    svg: <><path d="M9 19c-4 1.5-4-2.5-6-3" /><path d="M15 22v-3.5a3.4 3.4 0 0 0-1-2.6c3.3-.4 6.7-1.6 6.7-7.3a5.7 5.7 0 0 0-1.6-3.9 5.3 5.3 0 0 0-.1-3.9s-1.2-.4-4 1.5a13.7 13.7 0 0 0-7 0c-2.8-1.9-4-1.5-4-1.5a5.3 5.3 0 0 0-.1 3.9 5.7 5.7 0 0 0-1.6 4c0 5.6 3.4 6.8 6.7 7.2a3.4 3.4 0 0 0-1 2.6V22" /></>,
  },
  {
    name: "X",
    href: "https://x.com/beyondrecon",
    svg: <path d="M4 4l16 16M20 4 4 20" />,
  },
];

const Socials = () => (
  <div className="socials">
    {SOCIALS.map(s => (
      <a key={s.name} href={s.href} target="_blank" rel="noopener noreferrer" aria-label={s.name} className="social-link">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">{s.svg}</svg>
      </a>
    ))}
  </div>
);

const Footer = () => (
  <footer className="footer">
    <div className="wrap">
      <div className="footer-bot" style={{ borderTop: "none", paddingTop: 0 }}>
        <Brand />
        <Socials />
        <span>© 2026 BeyondRecon Security</span>
      </div>
    </div>
  </footer>
);

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "crimson",
  "showStats": true
}/*EDITMODE-END*/;

const App = () => {
  const [tweaks, setTweak] = window.useTweaks ? window.useTweaks(TWEAK_DEFAULTS) : [TWEAK_DEFAULTS, () => {}];

  useEffect(() => {
    document.documentElement.setAttribute("data-theme", tweaks.theme || "crimson");
  }, [tweaks.theme]);

  return (
    <>
      <Nav />
      <Hero />
      <Marquee />
      <Services />
      <Methodology />
      {tweaks.showStats && <Stats />}
      <CTA />
      <Footer />
      {window.TweaksPanel && (
        <window.TweaksPanel>
          <window.TweakSection title="Theme">
            <window.TweakRadio
              label="Accent color"
              value={tweaks.theme}
              onChange={v => setTweak("theme", v)}
              options={[
                { value: "crimson", label: "Crimson" },
                { value: "blue", label: "Blue" },
                { value: "green", label: "Matrix" },
                { value: "amber", label: "Amber" },
              ]}
            />
          </window.TweakSection>
          <window.TweakSection title="Sections">
            <window.TweakToggle label="Stats" value={tweaks.showStats} onChange={v => setTweak("showStats", v)} />
          </window.TweakSection>
        </window.TweaksPanel>
      )}
    </>
  );
};

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
