/* data.jsx — content for KASAU. Exports to window.
   Static marketing copy lives here; the open roles and all form submissions
   now come from / go to the serverless API under /api (see /api/_lib). */

const SERVICES = [
  { no: "01", tag: "BUILD", title: "Agentic Systems",
    blurb: "Multi-agent systems and autonomous workflows wired into your stack — planning, tool use, and orchestration that takes real work off your team.",
    tags: ["Multi-Agent", "Orchestration", "Tool Use", "Planning", "RAG"] },
  { no: "02", tag: "GUARD", title: "AI Safety & Alignment",
    blurb: "Guardrails, evaluation harnesses, and red-teaming so your models behave under adversarial input — and you can prove that they do.",
    tags: ["Guardrails", "Evals", "Red-Teaming", "Alignment", "Monitoring"] },
  { no: "03", tag: "PREDICT", title: "Prediction & Forecasting",
    blurb: "Forecasting and risk models that turn your history into decisions you can defend — built to be retrained as the world moves underneath them.",
    tags: ["Forecasting", "Time-Series", "Risk Models", "Uncertainty"] },
  { no: "04", tag: "UNDERSTAND", title: "Behavioral Science & ML",
    blurb: "Models grounded in how people actually decide — pairing behavioral science with machine learning to predict and shape real-world behavior.",
    tags: ["Behavioral Modeling", "Decisioning", "Causal", "Experimentation"] },
  { no: "05", tag: "INTEGRATE", title: "LLM Integration",
    blurb: "Production systems on the major LLM API providers — retrieval, prompting, evaluation, and cost control done properly, not stitched together.",
    tags: ["OpenAI", "Anthropic", "RAG", "Eval Pipelines", "Cost Control"] },
  { no: "06", tag: "HOST", title: "Local & Fine-Tuned LLMs",
    blurb: "Self-hosted and fine-tuned models for teams that need their data and their edge to stay in-house — tuning, distillation, and private deployment.",
    tags: ["Fine-Tuning", "Self-Hosted", "Distillation", "Private Deploy"] },
  { no: "07", tag: "MODEL", title: "Classical ML & Applied Math",
    blurb: "The mathematics under the hood — statistical modeling, optimization, and classical ML for the problems a language model is the wrong tool for.",
    tags: ["Statistics", "Optimization", "Classical ML", "Applied Math"] },
  { no: "08", tag: "SHIP", title: "Full Platforms",
    blurb: "End-to-end builds when you need them — the data, the model, the backend, and a frontend your users actually touch.",
    tags: ["Backend", "Frontend", "MLOps", "APIs", "Full-Stack"] },
];

const DOMAINS = [
  { n: "D-01", t: "Capital Markets", d: "Signals, forecasting, and execution research." },
  { n: "D-02", t: "Crypto & Digital Assets", d: "On-chain data, exchanges, and risk." },
  { n: "D-03", t: "Fraud & Risk", d: "Real-time anomaly detection and scoring." },
  { n: "D-04", t: "Fintech & Payments", d: "Underwriting, automation, and ledgers." },
  { n: "D-05", t: "AI Products & SaaS", d: "Agents, copilots, and platforms." },
  { n: "D-06", t: "Consumer & Behavioral", d: "Decisioning, personalization, and testing." },
];

const STEPS = [
  { n: "01", t: "Frame", d: "We pin down the problem, the data, and what 'good' means — before a line of model code is written." },
  { n: "02", t: "Prototype", d: "Fast model and agent prototypes against your real data, measured against a real baseline." },
  { n: "03", t: "Harden", d: "Evals, guardrails, and monitoring so the system holds up under drift and adversarial input." },
  { n: "04", t: "Operate", d: "We own iteration, retraining, and reliability. The system gets better, not just shipped." },
];

const VALUES = [
  { n: "V1", t: "Seniority", d: "Every engineer is mid-senior or above. You get people who have shipped real systems — not juniors learning on your problem." },
  { n: "V2", t: "Rigor", d: "Models are measured, evaluated, and stress-tested — not vibed. If we can't prove it works, we don't ship it." },
  { n: "V3", t: "Discretion", d: "Your data, your IP, and your edge stay yours. On-prem and private deployment when it matters." },
  { n: "V4", t: "Pragmatism", d: "We ship the simplest system that solves the problem — the right tool, whether that's an LLM or a regression." },
];

const ENGAGEMENTS = [
  { k: "E-01", mode: "Outstaff", t: "Embedded Engineers",
    d: "Senior AI, ML, and data engineers who join your team — your standups, your codebase, your roadmap — and own their part of it.",
    tags: ["Dedicated", "Your Stack", "Your Process", "Long-Term"] },
  { k: "E-02", mode: "Outsource", t: "Delivered End-to-End",
    d: "A focused team that takes the problem from discovery to delivery to operation, and hands you a working system — not a slide deck.",
    tags: ["Scoped", "Owned Outcomes", "Discovery → Ops", "Turnkey"] },
];

const DEPTH = [
  { no: "01", title: "The Full LLM Spectrum",
    blurb: "From the major API providers to self-hosted models we fine-tune and run on your own infrastructure — we pick the right one for your data, cost, and risk.",
    tags: ["API Providers", "Self-Hosted", "Fine-Tuning", "RAG"] },
  { no: "02", title: "Safety as Engineering",
    blurb: "Alignment, guardrails, and evaluation treated as core engineering, not an afterthought — so the system behaves under pressure and you can prove it.",
    tags: ["Alignment", "Guardrails", "Evals", "Red-Teaming"] },
  { no: "03", title: "Prediction, Grounded in Behavior",
    blurb: "Forecasting and predictive models built on a behavioral-science foundation — modeling not just the numbers, but how people actually decide.",
    tags: ["Forecasting", "Behavioral Science", "Causal", "Experimentation"] },
  { no: "04", title: "The Mathematics Underneath",
    blurb: "Deep classical ML, statistics, and optimization. When a language model is the wrong tool, we have the math to build the right one.",
    tags: ["Statistics", "Optimization", "Classical ML", "Applied Math"] },
  { no: "05", title: "Whole Platforms, Not Just Models",
    blurb: "When you need it, we build the system end-to-end — data, model, backend, and a frontend your users actually touch.",
    tags: ["Backend", "Frontend", "MLOps", "Full-Stack"] },
];

/* ── API client ───────────────────────────────────────────────
   Open roles and form submissions go through the serverless API.
   The UI only depends on these functions resolving (success) or
   throwing/returning null (error / missing), so nothing in the
   components changes if the backend implementation does. */

/* GET the careers list. → array of role summaries. */
async function fetchOpenings() {
  const res = await fetch("/api/openings");
  if (!res.ok) throw new Error("openings_unavailable");
  return res.json();
}

/* GET one role for #/job/<id>. → one record, or null if missing/closed. */
async function fetchOpening(id) {
  const res = await fetch("/api/openings/" + encodeURIComponent(id));
  if (res.status === 404) return null;
  if (!res.ok) throw new Error("opening_unavailable");
  return res.json();
}

/* Read a File into a base64 payload so the application can travel as one
   JSON body (kept small — the form guards file size). */
function fileToBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => {
      const result = String(reader.result || "");
      const comma = result.indexOf(",");
      resolve(comma === -1 ? result : result.slice(comma + 1)); // strip data: prefix
    };
    reader.onerror = () => reject(new Error("file_read_failed"));
    reader.readAsDataURL(file);
  });
}

const MAX_RESUME_BYTES = 4 * 1024 * 1024; // keep the JSON body under Vercel's limit

/* POST a job application → forwarded to Telegram by /api/apply.
   `data` shape: { name, email, linkedin, github, kaggle, coverLetter, resume }
   where `resume` is a File (or null). Resolves on success, throws on failure. */
async function submitApplication(jobId, data) {
  if (!data || !data.email || !data.name) throw new Error("missing_fields");

  let resume = null;
  if (data.resume) {
    if (data.resume.size > MAX_RESUME_BYTES) throw new Error("resume_too_large");
    resume = {
      name: data.resume.name,
      type: data.resume.type || "application/octet-stream",
      dataBase64: await fileToBase64(data.resume),
    };
  }

  const res = await fetch("/api/apply", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      jobId,
      name: data.name, email: data.email,
      linkedin: data.linkedin, github: data.github, kaggle: data.kaggle,
      coverLetter: data.coverLetter,
      resume,
    }),
  });
  if (!res.ok) throw new Error("apply_failed");
  return res.json();
}

/* POST a contact-form message → forwarded to Telegram by /api/contact.
   `data` shape: { name, email, company, need, message }. */
async function submitContact(data) {
  if (!data || !data.email || !data.name) throw new Error("missing_fields");
  const res = await fetch("/api/contact", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(data),
  });
  if (!res.ok) throw new Error("contact_failed");
  return res.json();
}

Object.assign(window, {
  SERVICES, DOMAINS, STEPS, VALUES, ENGAGEMENTS, DEPTH,
  fetchOpenings, fetchOpening, submitApplication, submitContact,
});
