const JOBS = [
  {
    id: "ml-ai-intern",
    title: "ML / AI Engineering Intern",
    tags: ["Internship", "Machine Learning", "Remote"],
    accentTag: "Machine Learning",
    whyBrainbox: "Cognitive decline affects 55 million people worldwide — most of them undiagnosed until it's too late. Brainbox is building AI to detect it early, through the way people speak and type, using the same signals trained clinicians use. We're a small team working on a genuinely hard problem where every improvement to the pipeline has real clinical stakes.",
    about: "You'll work on the intelligence layer of Brainbox: the pipeline that extracts cognitive biomarkers from speech and language, the models that score them, and the AI agents that power the experience. This is production ML work — you'll push code that runs in the product and engage with the full complexity of applied AI in a medical context.",
    whatYouDo: [
      "Train and improve models that score cognitive health across speech and language data",
      "Build and extend feature extraction pipelines for text and audio inputs",
      "Research cognitive markers from the literature and translate findings into working, testable code",
      "Evaluate LLM and model performance against annotated clinical transcripts and iterate",
      "Prototype new AI agent patterns for how Brainbox processes and understands user data",
    ],
    whatYouBring: [
      "Solid Python and hands-on ML experience",
      "Familiarity with LLMs — bonus for agentic systems and design patterns",
      "Familiarity with NLP — bonus for NLTK, spaCy",
      "Comfortable reading and reasoning from academic papers",
      "Use AI coding tools to move faster",
    ],
  },
  {
    id: "fullstack-intern",
    title: "Full Stack Engineering Intern",
    tags: ["Internship", "Full Stack", "Remote"],
    accentTag: "Full Stack",
    whyBrainbox: "Cognitive decline affects 55 million people worldwide — most of them undiagnosed until it's too late. Brainbox is building AI to detect it early, through the way people speak and type, using the same signals trained clinicians use. We're a small team working on a genuinely hard problem where every improvement to the pipeline has real clinical stakes.",
    about: "You'll work across the Brainbox backend and/or iOS app. One week you're designing a schema change or extending an API endpoint. The next you're building a new screen in the iOS app or wiring it up to a backend service. You'll take features from design all the way to shipped code.",
    whatYouDo: [
      "Design and extend REST endpoints that serve cognitive health data to the iOS app",
      "Build new screens and flows in the iOS app",
      "Own data modeling and schema work across the backend",
      "Integrate third-party services across auth, storage, and cloud infrastructure",
      "Help surface ML outputs as clear, useful experiences for users",
    ],
    whatYouBring: [
      "Experience with backend development in Python OR building iOS apps in Swift — bonus if both",
      "Understanding of how REST APIs work and how clients and servers communicate",
      "Familiar with SQL and relational databases",
      "Exposure to cloud platforms (GCP, AWS, Azure or similar)",
      "Comfortable using AI coding tools to move faster",
    ],
  },
];

const MAX_RESUME_BYTES = 10 * 1024 * 1024;

function ApplicationForm({ jobTitle }) {
  const [form, setForm] = React.useState({ name: "", email: "", why: "", link: "" });
  const [resumeFile, setResumeFile] = React.useState(null);
  const [fileError, setFileError] = React.useState("");
  const [wordCount, setWordCount] = React.useState(0);
  const [status, setStatus] = React.useState("idle"); // idle | submitting | success | error
  const [errorMessage, setErrorMessage] = React.useState("");
  const fileInputRef = React.useRef(null);

  const updateField = (key, val) => {
    setForm(f => ({ ...f, [key]: val }));
    if (status === "error") { setStatus("idle"); setErrorMessage(""); }
  };

  // Separate handler for the word-limited "why" textarea.
  // Mirrors old behavior: allow the change if words ≤ 100 OR the user is deleting text.
  const handleWhyChange = (e) => {
    const val = e.target.value;
    const words = val.trim().split(/\s+/).filter(Boolean);
    if (words.length <= 100 || val.length < form.why.length) {
      setWordCount(val.trim() ? words.length : 0);
      setForm(f => ({ ...f, why: val }));
      if (status === "error") { setStatus("idle"); setErrorMessage(""); }
    }
  };

  const handleFileChange = (e) => {
    const file = e.target.files[0];
    if (!file) return;
    if (file.size > MAX_RESUME_BYTES) {
      setFileError("File exceeds 10 MB. Please choose a smaller file.");
      e.target.value = "";
      return;
    }
    setFileError("");
    setResumeFile(file);
    if (status === "error") { setStatus("idle"); setErrorMessage(""); }
  };

  const handleRemoveFile = (e) => {
    e.stopPropagation();
    setResumeFile(null);
    setFileError("");
    if (fileInputRef.current) fileInputRef.current.value = "";
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setStatus("submitting");
    setErrorMessage("");
    try {
      await window.Api.submitApplication(
        {
          name: form.name.trim(),
          email: form.email.trim(),
          role: jobTitle,
          message: form.why.trim() || undefined,
          linkedin_url: form.link.trim() || undefined,
        },
        resumeFile,
      );
      setStatus("success");
    } catch (err) {
      const { ApiError } = window.Api;
      if (err instanceof ApiError && err.code === "invalid_fields") {
        setErrorMessage("Please check your details and try again.");
      } else {
        setErrorMessage("Something went wrong. Please try again.");
      }
      setStatus("error");
    }
  };

  const submitting = status === "submitting";
  const isValid = form.name.trim() && form.email.trim() && form.why.trim() && resumeFile && !fileError;

  if (status === "success") {
    return (
      <div className="success-msg">
        <div className="check-circle">✓</div>
        <h3 className="serif">Application received</h3>
        <p>Thanks for your interest in Brainbox. We'll be in touch soon.</p>
      </div>
    );
  }

  return (
    <form onSubmit={handleSubmit}>
      <div className="form-field">
        <label>Full name <span className="req">*</span></label>
        <input
          type="text"
          placeholder="Jane Smith"
          required
          value={form.name}
          onChange={e => updateField("name", e.target.value)}
          disabled={submitting}
        />
      </div>
      <div className="form-field">
        <label>Email <span className="req">*</span></label>
        <input
          type="email"
          placeholder="jane@example.com"
          required
          value={form.email}
          onChange={e => updateField("email", e.target.value)}
          disabled={submitting}
        />
      </div>
      <div className="form-field">
        <label>Why Brainbox? <span className="req">*</span></label>
        <textarea
          placeholder="In 100 words or fewer, tell us why this role and this problem resonate with you."
          required
          value={form.why}
          onChange={handleWhyChange}
          disabled={submitting}
        />
        <div className="hint" style={wordCount >= 95 ? { color: "#c53030" } : {}}>{wordCount} / 100 words</div>
      </div>
      <div className="form-field">
        <label>LinkedIn, GitHub, or portfolio</label>
        <input
          type="url"
          placeholder="https://"
          value={form.link}
          onChange={e => updateField("link", e.target.value)}
          disabled={submitting}
        />
      </div>
      <div className="form-field">
        <label>Resume <span className="req">*</span></label>
        <label
          className={`file-upload ${resumeFile ? "has-file" : ""} ${submitting ? "disabled" : ""}`}
          htmlFor={submitting ? undefined : "resume-upload"}
          style={submitting ? { opacity: 0.6, pointerEvents: "none" } : {}}
        >
          {resumeFile ? (
            <div className="fu-file">
              📄 {resumeFile.name}
              <button
                type="button"
                onClick={handleRemoveFile}
                style={{ marginLeft: 8, background: "none", border: "none", cursor: "pointer", fontSize: 12, color: "var(--ink-mute)" }}
                aria-label="Remove file"
              >
                ✕
              </button>
            </div>
          ) : (
            <>
              <div className="fu-label"><strong>Click to upload</strong> or drag and drop</div>
              <div className="fu-hint">PDF, DOC, or DOCX · Max 10 MB</div>
            </>
          )}
          <input
            id="resume-upload"
            ref={fileInputRef}
            type="file"
            accept=".pdf,.doc,.docx"
            style={{ display: "none" }}
            onChange={handleFileChange}
            disabled={submitting}
          />
        </label>
        {fileError && (
          <p style={{ marginTop: 6, fontSize: 13, color: "#c53030" }}>{fileError}</p>
        )}
      </div>

      <button
        type="submit"
        className="submit-btn"
        disabled={!isValid || submitting}
        style={(!isValid || submitting) ? { opacity: 0.6, cursor: "not-allowed" } : {}}
      >
        {submitting ? "Submitting…" : "Submit application →"}
      </button>

      {status === "error" && (
        <p style={{ marginTop: 12, fontSize: 14, color: "#c53030", textAlign: "center" }}>
          {errorMessage}
        </p>
      )}
    </form>
  );
}

function JobListing({ onSelectJob }) {
  useReveal();
  return (
    <>
      <Nav currentPage="careers" />

      <section className="careers-hero">
        <div className="container">
          <div className="reveal in"><span className="eyebrow">Careers</span></div>
          <h1 className="serif reveal in delay-1" style={{ marginTop: 22, maxWidth: '22ch' }}>
            Where you come in.
          </h1>
          <p className="lead reveal in delay-2" style={{ marginTop: 28 }}>
            We're a small team working on a genuinely hard problem, where every improvement
            to the pipeline has real clinical stakes. If the work sounds like yours, we'd love to hear from you.
          </p>
        </div>
      </section>

      <section className="section" id="roles" style={{ paddingTop: 40 }}>
        <div className="container">
          <div className="roles-grid">
            {JOBS.map((job, idx) => (
              <div
                key={job.id}
                className={`role-card reveal delay-${idx + 1}`}
                onClick={() => onSelectJob(job.id)}
                role="button"
                tabIndex={0}
                onKeyDown={e => e.key === "Enter" && onSelectJob(job.id)}
              >
                <div>
                  <div className="role-card-title">{job.title}</div>
                  <div className="role-card-meta">
                    {job.tags.map(t => (
                      <span key={t} className={`role-card-tag ${t === job.accentTag ? "accent" : ""}`}>{t}</span>
                    ))}
                  </div>
                </div>
                <div className="role-card-arrow">→</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      <Footer />
    </>
  );
}

function JobDetail({ jobId, onBack }) {
  useReveal();
  const job = JOBS.find(j => j.id === jobId);

  React.useEffect(() => {
    window.scrollTo(0, 0);
  }, [jobId]);

  if (!job) return null;

  return (
    <>
      <Nav currentPage="careers" />

      <section className="job-detail-hero">
        <div className="container">
          <button className="job-back reveal in" onClick={onBack}>← All open roles</button>
          <h1 className="serif reveal in delay-1" style={{ marginTop: 24, maxWidth: '22ch' }}>
            {job.title}
          </h1>
          <div className="job-tags reveal in delay-2">
            {job.tags.map(t => (
              <span key={t} className={`job-tag ${t === job.accentTag ? "accent" : ""}`}>{t}</span>
            ))}
          </div>
        </div>
      </section>

      <section className="section" style={{ paddingTop: 60 }}>
        <div className="container">
          <div className="job-layout">
            <div className="job-description reveal">
              <h4>Why Brainbox?</h4>
              <p>{job.whyBrainbox}</p>
              <h4>About the role</h4>
              <p>{job.about}</p>
              <h4>What you'll do</h4>
              <ul>
                {job.whatYouDo.map((item, i) => <li key={i}>{item}</li>)}
              </ul>
              <h4>What you bring</h4>
              <ul>
                {job.whatYouBring.map((item, i) => <li key={i}>{item}</li>)}
              </ul>
            </div>
            <div className="reveal delay-1">
              <div className="apply-card">
                <h3 className="serif">Apply for this role</h3>
                <div className="apply-sub">We read every application. No cover letter needed — just the form below.</div>
                <ApplicationForm jobTitle={job.title} />
              </div>
            </div>
          </div>
        </div>
      </section>

      <Footer />
    </>
  );
}

function CareersApp() {
  const [selectedJob, setSelectedJob] = React.useState(null);

  if (selectedJob) {
    return <JobDetail jobId={selectedJob} onBack={() => { setSelectedJob(null); window.scrollTo(0, 0); }} />;
  }
  return <JobListing onSelectJob={setSelectedJob} />;
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<CareersApp />);
