/* Common Works — interior pages: What We Do, Team, Careers */
const { useState: useStateP, useRef: useRefP, useEffect: useEffectP } = React;

function slugify(s) {
  return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");
}

/* ============================ WHAT WE DO ============================ */
function WhatWeDo() {
  const CW = window.CW;
  return (
    <div data-screen-label="What We Do">
      <section className="page-hero">
        <div className="wrap-wide">
          <Reveal stagger>
            <div className="eyebrow">What we do</div>
            <h1>Investment thesis → operating plan → deployed capability.</h1>
            <p className="lead">We help private equity sponsors identify AI-related opportunity and risk, translate those findings into underwritable value creation plans, and work directly with portfolio company leadership to build and deploy the products, workflows, and systems needed to execute.</p>
          </Reveal>
        </div>
      </section>

      {/* how we work — offer lines only */}
      <section className="sec band-cream2">
        <div className="wrap-wide">
          <Reveal className="sec-head">
            <div className="eyebrow">How we work</div>
            <h2 className="display">Clear, scoped engagements and deliverables.</h2>
            <p className="lead">Each can stand alone or compose into an end-to-end program.</p>
          </Reveal>

          <Reveal style={{ marginTop: 32 }}>
            <div className="offers-cols">
              <div>
                <div className="eyebrow no-rule" style={{ marginBottom: 20 }}>Pre-deal</div>
                <div className="offers-cards offers-cards--pre">
                  {CW.offers.preDeal.map((o, i) =>
                    <div className="card" key={i}>
                      <h3>{o.name}</h3>
                      <p>{o.desc}</p>
                      {o.bullets && <ul style={{ margin: "12px 0 0", paddingLeft: 18, display: "flex", flexDirection: "column", gap: 5 }}>
                        {o.bullets.map((b, j) => <li key={j} style={{ fontSize: 14, color: "var(--ink-2)", lineHeight: 1.5 }}>{b}</li>)}
                      </ul>}
                    </div>
                  )}
                </div>
              </div>
              <div>
                <div className="eyebrow no-rule" style={{ marginBottom: 20 }}>Post-close</div>
                <div className="offers-cards offers-cards--post">
                  {CW.offers.postClose.map((o, i) =>
                    <div className="card" key={i}>
                      <h3>{o.name}</h3>
                      <p>{o.desc}</p>
                      {o.bullets && <ul style={{ margin: "12px 0 0", paddingLeft: 18, display: "flex", flexDirection: "column", gap: 5 }}>
                        {o.bullets.map((b, j) => <li key={j} style={{ fontSize: 14, color: "var(--ink-2)", lineHeight: 1.5 }}>{b}</li>)}
                      </ul>}
                    </div>
                  )}
                </div>
              </div>
            </div>
          </Reveal>
        </div>
      </section>

      {/* what we're not */}
      <section className="sec">
        <div className="wrap-wide split">
          <Reveal>
            <h2 className="display" style={{ fontSize: "clamp(28px,3.2vw,42px)", marginTop: 20 }}>A technical operating firm.

            </h2>
          </Reveal>
          <Reveal className="split-points">
            <div className="split-point"><span className="sp-mark">×</span><div><h4>Not a traditional consultancy</h4><p>Every deliverable we produce, we're prepared to execute.</p></div></div>
            <div className="split-point"><span className="sp-mark">×</span><div><h4>Not a dev shop</h4><p>Engineering is embedded in a thesis-to-execution model, not bodies for hire.</p></div></div>
            <div className="split-point"><span className="sp-mark">×</span><div><h4>Not a SaaS point solution</h4><p>Product and tooling enable the work; the firm functions like an operating partner.</p></div></div>
          </Reveal>
        </div>
      </section>

      <CTABand />
    </div>);

}

/* ============================ TEAM ============================ */
function PersonCard({ p }) {
  return (
    <div className="person">
      <img className="person-photo" src={p.img} alt={p.name} />
      <div className="person-body">
        <div className="person-name">{p.name}</div>
        <div className="person-role">{p.role}</div>
        {p.bio &&
        <div className="person-bio">
            {p.bio.map((b, j) => <p key={j}>{b}</p>)}
          </div>
        }
        <div className="person-links">
          <a className="iconbtn" href={p.linkedin} target="_blank" rel="noopener noreferrer" aria-label={p.name + " on LinkedIn"}>
            <LinkedIn />
          </a>
          {p.email &&
          <a className="iconbtn" href={"mailto:" + p.email} aria-label={"Email " + p.name}>
              <Mail />
            </a>
          }
        </div>
      </div>
    </div>);

}

function Team() {
  const CW = window.CW;
  return (
    <div data-screen-label="Team">
      <section className="page-hero">
        <div className="wrap-wide">
          <Reveal stagger>
            <div className="eyebrow">Team</div>
            <h1>Senior judgment. Hands on the keyboard.</h1>
            <p className="lead">Common Works is built by AI practitioners from top PE firms who have worked & shipped at the intersection of investment judgment, product strategy, and engineering.</p>
          </Reveal>
        </div>
      </section>

      <section className="sec">
        <div className="wrap-wide">
          <Reveal className="sec-head" style={{ marginBottom: 40 }}>
            <h2 className="display">Leadership</h2>
          </Reveal>
          <Reveal className="team-grid" stagger>
            {CW.leadership.map((p, i) => <PersonCard key={i} p={p} />)}
          </Reveal>
        </div>
      </section>

      <section className="sec band-cream2">
        <div className="wrap-wide">
          <Reveal className="sec-head" style={{ marginBottom: 40 }}>
            <h2 className="display">Advisors</h2>
          </Reveal>
          <Reveal className="team-grid" stagger>
            {CW.advisors.map((p, i) => <PersonCard key={i} p={p} />)}
          </Reveal>
        </div>
      </section>

      <section className="sec-sm">
        <div className="wrap-wide" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 24, flexWrap: "wrap" }}>
          <div>
            <div className="eyebrow" style={{ marginBottom: 14 }}>Work with us</div>
            <h3 className="serif" style={{ fontSize: 28, letterSpacing: "-.01em", maxWidth: "22ch" }}>
              Building the network of engineers and operators who deploy alongside us.
            </h3>
          </div>
          <a className="btn btn-primary" href="#/careers" onClick={(e) => {e.preventDefault();window.__go("careers");}}>
            See open roles <Arrow />
          </a>
        </div>
      </section>

      <CTABand />
    </div>);

}

/* ============================ CAREERS ============================ */
function RoleRow({ role, onClick }) {
  return (
    <div className="role-row" onClick={onClick}>
      <div className="role-main">
        <h3>{role.title}</h3>
      </div>
      <div className="role-right">
        <div className="role-meta">
          <span className="tag">{role.loc}</span>
          <span className="tag" style={{ background: "transparent", color: "var(--ink-3)", border: "1px solid var(--line)" }}>{role.type}</span>
        </div>
        <span className="role-toggle"><Plus /></span>
      </div>
    </div>);

}

function RoleModal({ role, onClose }) {
  const [copied, setCopied] = useStateP(false);

  useEffectP(() => {
    document.body.classList.add("modal-open");
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => {
      document.body.classList.remove("modal-open");
      window.removeEventListener("keydown", onKey);
    };
  }, []);

  const copyLink = () => {
    const url = location.origin + location.pathname + "#/careers/" + slugify(role.title);
    navigator.clipboard.writeText(url).catch(() => {}).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    });
  };

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose} aria-label="Close">
          <span style={{ display: "flex", transform: "rotate(45deg)" }}><Plus /></span>
        </button>
        <div className="modal-body">
          <div className="modal-head">
            <h2>{role.title}</h2>
            <div className="modal-meta-row">
              <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
                <span className="tag">{role.loc}</span>
                <span className="tag" style={{ background: "transparent", color: "var(--ink-3)", border: "1px solid var(--line)" }}>{role.type}</span>
              </div>
              <button className={"share-btn" + (copied ? " copied" : "")} onClick={copyLink} aria-label="Copy link to this role">
                {copied ? "Copied!" : <Share />}
              </button>
            </div>
            <p className="lead" style={{ margin: 0 }}>{role.blurb}</p>
          </div>

          <div className="modal-section">
            <h5>About Common Works</h5>
            {window.CW.about.map((p, i) => <p key={i} style={i > 0 ? {marginTop: 12} : {}}>{p}</p>)}
          </div>

          <div className="modal-section">
            <h5>The Role</h5>
            {role.roleDesc.map((p, i) => <p key={i} style={i > 0 ? {marginTop: 12} : {}}>{p}</p>)}
          </div>

          <div className="modal-section">
            <h5>Key Responsibilities</h5>
            <ul>{role.resp.map((r, i) => <li key={i}>{r}</li>)}</ul>
          </div>

          <div className="modal-section">
            <h5>Qualifications</h5>
            <p className="modal-subhead">Required</p>
            <ul>{role.required.map((r, i) => <li key={i}>{r}</li>)}</ul>
            <p className="modal-subhead" style={{marginTop: 20}}>Preferred</p>
            <ul>{role.preferred.map((r, i) => <li key={i}>{r}</li>)}</ul>
          </div>

          <div className="modal-apply">
            <div className="eyebrow" style={{ marginBottom: 10 }}>Apply</div>
            <h3 className="serif" style={{ fontSize: 28, letterSpacing: "-.01em", marginBottom: 8 }}>Join the network.</h3>
            <p className="lead" style={{ marginBottom: 32 }}>Tell us who you are and what you've shipped.</p>
            <ApplyForm preselectedRole={role.title} />
          </div>
        </div>
      </div>
    </div>);

}

function ApplyForm({ preselectedRole = null }) {
  const roles = window.CW.roles;
  const [vals, setVals] = useStateP({ name: "", location: "", email: "", linkedin: "", github: "", proud: "" });
  const [rolesOfInterest, setRolesOfInterest] = useStateP(preselectedRole ? [preselectedRole] : []);
  const [file, setFile] = useStateP(null);
  const [errs, setErrs] = useStateP({});
  const [sent, setSent] = useStateP(false);
  const [submitting, setSubmitting] = useStateP(false);
  const [submitError, setSubmitError] = useStateP(null);
  const inputRef = useRefP(null);

  const set = (k) => (e) => setVals({ ...vals, [k]: e.target.value });
  const toggleRole = (title) => setRolesOfInterest(prev =>
    prev.includes(title) ? prev.filter(r => r !== title) : [...prev, title]
  );

  const submit = async (e) => {
    e.preventDefault();
    const er = {};
    if (!vals.name.trim()) er.name = "Required";
    if (!vals.location.trim()) er.location = "Required";
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(vals.email)) er.email = "Valid email required";
    if (!vals.linkedin.trim()) er.linkedin = "Required";
    if (rolesOfInterest.length === 0) er.roles = "Select at least one role";
    if (!file) er.file = "Resume required";
    setErrs(er);
    if (Object.keys(er).length > 0) return;

    setSubmitting(true);
    setSubmitError(null);
    try {
      const resumeBase64 = await new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => resolve(reader.result.split(",")[1]);
        reader.onerror = reject;
        reader.readAsDataURL(file);
      });

      const res = await fetch("/api/apply", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ...vals, roles: rolesOfInterest, resumeBase64, resumeName: file.name }),
      });

      if (!res.ok) throw new Error("Submission failed");
      setSent(true);
    } catch {
      setSubmitError("Something went wrong. Please email us directly at jason@commonworks.ai.");
    } finally {
      setSubmitting(false);
    }
  };

  if (sent) {
    return (
      <div className="form-card">
        <div className="form-success">
          <div className="fs-mark"><Check /></div>
          <h3 className="serif" style={{ fontSize: 28, letterSpacing: "-.01em", marginBottom: 12 }}>Application received</h3>
          <p className="muted" style={{ maxWidth: "44ch", margin: "0 auto" }}>
            Thank you, {vals.name.split(" ")[0]}. We'll be in touch if there's a strong fit.
          </p>
        </div>
      </div>);

  }

  const fld = (k, label, ph, opt) =>
  <div className={"field" + (k === "github" ? "" : "")}>
      <label>{label}{opt && <span className="opt"> (optional)</span>}</label>
      <input value={vals[k]} onChange={set(k)} placeholder={ph}
    className={errs[k] ? "err" : ""} />
      {errs[k] && <span className="errmsg">{errs[k]}</span>}
    </div>;


  return (
    <form className="form-card" onSubmit={submit} noValidate>
      <div className="form-grid">
        {fld("name", "Full Name", "Ford DePloy")}
        {fld("location", "Current Location", "New York, NY")}
        {fld("email", "Email", "ford.deploy@gmail.com")}
        {fld("linkedin", "LinkedIn", "linkedin.com/in/forddeploy")}
        <div className="field full">
          <label>Role(s) of Interest</label>
          <div className="roles-chips">
            {roles.map(r =>
              <button key={r.title} type="button"
                className={"role-chip" + (rolesOfInterest.includes(r.title) ? " selected" : "")}
                onClick={() => toggleRole(r.title)}
                aria-pressed={rolesOfInterest.includes(r.title)}>
                {r.title}
              </button>
            )}
          </div>
          {errs.roles && <span className="errmsg">{errs.roles}</span>}
        </div>
        <div className="field full">
          <label>GitHub <span className="opt">(optional)</span></label>
          <input value={vals.github} onChange={set("github")} placeholder="github.com/forddeploy" />
        </div>
        <div className="field full">
          <label>What are you most proud of? <span className="opt">(optional)</span></label>
          <input value={vals.proud} onChange={set("proud")} placeholder="" />
        </div>

        <div className={"dropzone" + (file ? " has" : "")}
        onClick={() => inputRef.current && inputRef.current.click()}
        onDragOver={(e) => e.preventDefault()}
        onDrop={(e) => {e.preventDefault();if (e.dataTransfer.files[0]) setFile(e.dataTransfer.files[0]);}}>
          <div style={{ color: file ? "var(--forest)" : "var(--ink-3)", display: "flex", justifyContent: "center", marginBottom: 10 }}>
            <Upload />
          </div>
          <div className="dz-title">{file ? file.name : "Upload your resume"}</div>
          <div className="dz-sub">{file ? "Click to replace" : "PDF or DOCX · drag & drop or browse"}</div>
          <input ref={inputRef} type="file" accept=".pdf,.doc,.docx" style={{ display: "none" }}
          onChange={(e) => e.target.files[0] && setFile(e.target.files[0])} />
        </div>
        {errs.file && <span className="errmsg" style={{ gridColumn: "1 / -1", marginTop: -10 }}>{errs.file}</span>}
      </div>

      <div className="form-actions">
        <p className="form-note">By applying you consent to Common Works contacting you about opportunities.</p>
        {submitError && <p className="errmsg" style={{ marginBottom: 12 }}>{submitError}</p>}
        <button type="submit" className="btn btn-primary" disabled={submitting}>
          {submitting ? "Submitting…" : <span>Submit application <Arrow /></span>}
        </button>
      </div>
    </form>);

}

function Careers() {
  const CW = window.CW;
  const C = CW.careersIntro;
  const V = CW.careersValues;
  const initSlug = ((window.location.hash || "").replace(/^#\/?/, "").split("/")[1] || "");
  const [modalRole, setModalRole] = useStateP(
    initSlug ? (CW.roles.find(r => slugify(r.title) === initSlug) || null) : null
  );

  const openModal = (role) => {
    history.replaceState(null, "", "#/careers/" + slugify(role.title));
    setModalRole(role);
  };
  const closeModal = () => {
    history.replaceState(null, "", "#/careers");
    setModalRole(null);
  };

  return (
    <div data-screen-label="Careers">
      <section className="page-hero">
        <div className="wrap-wide">
          <Reveal stagger>
            <div className="eyebrow">{C.eyebrow}</div>
            <h1>{C.headline}</h1>
            <p className="lead">{C.body}</p>
          </Reveal>
        </div>
      </section>

      <section className="sec band-forest">
        <div className="wrap-wide">
          <Reveal stagger>
            <div className="eyebrow careers-eyebrow">{V.eyebrow}</div>
            <h2 className="display" style={{ color: "var(--cream-on-forest)", fontSize: "clamp(28px,3.5vw,46px)", marginTop: 16, maxWidth: "18ch" }}>{V.headline}</h2>
            {V.body.map((p, i) => <p key={i} className="lead" style={{ color: "var(--mute-on-forest)", marginTop: i === 0 ? 20 : 16, maxWidth: "58ch" }}>{p}</p>)}
          </Reveal>
          <Reveal className="careers-values" stagger style={{ marginTop: 52 }}>
            {V.values.map((v, i) =>
              <div className="careers-value" key={i}>
                <div className="cv-label">{v.label}</div>
                <p>{v.body}</p>
              </div>
            )}
          </Reveal>
        </div>
      </section>

      <section className="sec">
        <div className="wrap-wide">
          <Reveal className="sec-head" style={{ marginBottom: 36 }}>
            <h2 className="display">Open roles</h2>
          </Reveal>
          <Reveal style={{ borderTop: "1px solid var(--line)" }}>
            {CW.roles.map((r, i) =>
            <RoleRow key={i} role={r} onClick={() => openModal(r)} />
            )}
          </Reveal>
        </div>
      </section>

      <section className="sec band-cream2" id="apply">
        <div className="wrap-wide" style={{ maxWidth: 880 }}>
          <Reveal className="sec-head" style={{ marginBottom: 36, textAlign: "left" }}>
            <div className="eyebrow">Apply</div>
            <h2 className="display">Join the network.</h2>
            <p className="lead">Tell us who you are and what you've shipped.</p>
          </Reveal>
          <Reveal>
            <ApplyForm />
          </Reveal>
        </div>
      </section>

      {modalRole && <RoleModal role={modalRole} onClose={closeModal} />}

      <CTABand />
    </div>);

}

/* ============================ LEGAL ============================ */
function Legal({ doc }) {
  return (
    <div data-screen-label={doc.title}>
      <section className="page-hero">
        <div className="wrap-wide">
          <Reveal stagger>
            <div className="eyebrow">Legal</div>
            <h1>{doc.title}</h1>
            <p className="legal-updated">Last updated {doc.updated}</p>
            <p className="lead">{doc.intro}</p>
          </Reveal>
        </div>
      </section>

      <section className="sec">
        <div className="wrap-wide">
          <Reveal className="legal-prose" stagger>
            {doc.sections.map((s, i) =>
            <div className="legal-block" key={i}>
                <h2>{s.h}</h2>
                {s.p.map((para, j) => <p key={j}>{para}</p>)}
              </div>
            )}
          </Reveal>
        </div>
      </section>

      <CTABand />
    </div>);

}

Object.assign(window, { WhatWeDo, Team, Careers, Legal });