const { Section, SectionHeader, MediaFeatureCard, AlternatingFeature, ExtensionCard, FeatureIndex, VerticalTabs, CodeBlock, LogoMarquee, MetricRow, TestimonialCard, ClosingCTA, Button } = window.SamsonAILabDesignSystem_8f27a2;

function MediaBlock() {
  const { RunPeek } = window;
  return (
    <Section>
      <SectionHeader heading="See what happened, not what should have" body="Every attempt is recorded with its inputs, outputs, logs and timings. Replay a run against a new deployment without touching your app." linkLabel="Run history docs" arrow="external" />
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(320px, 1fr))", gap: "var(--gap-cards)" }}>
        <MediaFeatureCard title="Every run, replayable" body="Inspect inputs, outputs, logs and timings for any attempt, then replay it." media={<RunPeek header={false} style={{ borderRadius: 0, border: 0, borderTop: "1px solid var(--color-grid-hairline)" }} />} />
        <MediaFeatureCard title="Failures name themselves" body="A failed attempt shows the error, the attempt number and the backoff before the next one." media={<CodeBlock onPage lineNumbers padding="16px" code={["// attempt 2 of 3 — retrying in 4s", "TimeoutError: model.summarize exceeded 30s", "  at summarize (src/tasks/summarize.ts:14:22)", "  attempt: 2", "  next_attempt_at: 2026-03-04T11:02:19Z"].join("\n")} />} />
      </div>
    </Section>
  );
}

function FeatureBlocks() {
  const { RunPeek } = window;
  return (
    <Section>
      <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-32)" }}>
        <AlternatingFeature
          eyebrow="Live updates"
          eyebrowColor="var(--color-cat-blue)"
          heading="Show task progress anywhere in your app"
          body="Subscribe to a run and render its status and metadata as it changes, so people can see what's happening instead of guessing."
          linkLabel="Realtime docs"
          visual={<RunPeek />}
          caption="Run status streaming into a customer-facing view"
        />
        <AlternatingFeature
          reverse
          eyebrow="Concurrency"
          eyebrowColor="var(--color-cat-purple)"
          heading="Give every tenant its own lane"
          body="Named queues take a concurrency limit, so one noisy customer cannot starve the rest. Limits are set in code and enforced by the platform."
          linkLabel="Queues docs"
          visual={<CodeBlock code={["// One queue per tenant, each limited to two parallel runs", 'import { queue, task } from "@samson/sdk";', "", "const tenantQueue = queue({", '  name: "tenant",', "  concurrencyLimit: 2,", "});", "", "export const ingest = task({", '  id: "ingest-documents",', "  queue: tenantQueue,", "  run: async ({ tenantId, docs }) => {", "    for (const doc of docs) await index(tenantId, doc);", "  },", "});"].join("\n")} />}
          caption="Concurrency is declared in code and enforced per queue"
        />
      </div>
    </Section>
  );
}

function ExtensionsBlock() {
  return (
    <Section>
      <SectionHeader heading="Extend it where you need to" body="The runtime is open. Add a language, a browser, a schedule or your own infrastructure without leaving the platform." linkLabel="Extensions" arrow="external" />
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))", gridAutoRows: "1fr", gap: "var(--gap-cards)" }}>
        {window.EXTENSIONS.map((e) => (
          <ExtensionCard key={e.title} {...e} />
        ))}
      </div>
    </Section>
  );
}

function IndexBlock() {
  return (
    <Section>
      <SectionHeader heading="Everything included" body="No add-ons and no per-seat gates on the platform features. This is the full list." linkLabel="See pricing" />
      <FeatureIndex columns={window.FEATURE_INDEX} />
    </Section>
  );
}

const RELIABILITY = {
  retry: { label: "retry", mono: true, code: ["// Exponential backoff, configured per task", "export const summarize = task({", '  id: "summarize-document",', "  retry: { maxAttempts: 3, factor: 2, minTimeoutInMs: 1000 },", "  run: async ({ documentId }) => model.summarize(documentId),", "});"].join("\n") },
  idempotency: { label: "idempotencyKey", mono: true, code: ["// The same key never triggers twice", "await summarize.trigger(", "  { documentId },", '  { idempotencyKey: "doc-" + documentId }', ");"].join("\n") },
  checkpoints: { label: "Checkpoints", code: ["// Work already done survives a redeploy mid-run", "export const migrate = task({", '  id: "migrate-accounts",', "  run: async ({ accounts }) => {", "    for (const account of accounts) {", "      await step.run(account.id, () => move(account));", "    }", "  },", "});"].join("\n") },
  alerts: { label: "Alerts", code: ["// Failures route to a channel, not a dashboard nobody opens", 'import { alerts } from "@samson/sdk";', "", 'alerts.on("run.failed", { channel: "#oncall" });'].join("\n") },
};

function TabsBlock() {
  const items = Object.entries(RELIABILITY).map(([id, v]) => ({ id, label: v.label, mono: v.mono }));
  return (
    <Section>
      <SectionHeader heading="Reliability is the product" body="Retries, idempotency, checkpoints and alerting are part of the task definition rather than a layer you assemble yourself." linkLabel="Reliability docs" arrow="external" />
      <VerticalTabs items={items}>{(id) => <div key={id} className="ds-fade"><CodeBlock onPage padding="0" code={RELIABILITY[id].code} /></div>}</VerticalTabs>
    </Section>
  );
}

function ProofBlock() {
  const [expanded, setExpanded] = React.useState(false);
  return (
    <React.Fragment>
      <Section>
        <LogoMarquee framing="Teams running production workloads on Samson AI Lab" rows={window.LOGO_ROWS} />
      </Section>
      <Section>
        <p style={{ maxWidth: 560, fontSize: "var(--text-2xl)", lineHeight: "var(--leading-2xl)", letterSpacing: "var(--tracking-2xl)", color: "var(--color-text-bright)", marginBottom: "var(--space-8)", textWrap: "pretty" }}>The platform is open source, and the parts you depend on are readable.</p>
        <MetricRow
          items={[
            { icon: "star", color: "var(--color-cat-sun)", value: "16.1k", label: "GitHub stars" },
            { icon: "git-pull-request", color: "var(--color-cat-indigo)", value: "1,284", label: "Merged pull requests" },
            { icon: "users", color: "var(--color-cat-teal)", value: "6.4k", label: "Developers in Discord" },
            { icon: "package", color: "var(--color-cat-green)", value: "Weekly", label: "Release cadence" },
          ]}
        />
      </Section>
      <Section>
        <SectionHeader heading="What teams say" body="Quotes below are illustrative placeholders from the source document — replace them with attributable customer quotes before publishing." linkLabel="Customer stories" arrow="external" />
        <div style={{ position: "relative", maxHeight: expanded ? "none" : 340, overflow: "hidden" }}>
          <div style={{ columnCount: 3, columnGap: "var(--space-4)" }}>
            {window.TESTIMONIALS.map((t) => (
              <TestimonialCard key={t.name} {...t} />
            ))}
          </div>
          {expanded ? null : <div aria-hidden="true" style={{ position: "absolute", left: 0, right: 0, bottom: 0, height: 140, background: "linear-gradient(to bottom, transparent, var(--color-background-deep))" }} />}
        </div>
        <div style={{ display: "flex", justifyContent: "center", marginTop: "var(--space-6)" }}>
          <Button variant="tertiary" size="medium" onClick={() => setExpanded(!expanded)}>{expanded ? "Show less" : "Read more"}</Button>
        </div>
      </Section>
    </React.Fragment>
  );
}

function CTABlock() {
  return (
    <Section texture rule={false}>
      <ClosingCTA
        heading="Ready to build?"
        body="Deploy your first task in a few minutes. No infrastructure to set up."
        ctaLabel="Start for free"
        cards={[
          { heading: "Pricing", body: "Pay for execution time, not for idle servers.", linkLabel: "See pricing" },
          { heading: "Self-hosting", body: "Run the whole platform on your own infrastructure.", linkLabel: "Self-hosting guide" },
        ]}
      />
    </Section>
  );
}

Object.assign(window, { MediaBlock, FeatureBlocks, ExtensionsBlock, IndexBlock, TabsBlock, ProofBlock, CTABlock });
