import { createFileRoute } from "@tanstack/react-router";
import { useState } from "react";
import { PageHero } from "@/components/site/page-hero";
import { BeforeAfter } from "@/components/site/before-after";
import { FinalCta } from "@/components/site/final-cta";
import { Reveal } from "@/components/site/reveal";
import { Container, Kicker } from "@/components/site/section";
import { Button } from "@/components/ui/button";
import { Field, Select } from "@/components/ui/field";
import { pageHead } from "@/lib/seo";
import { enterThePast } from "@/lib/timeless";

export const Route = createFileRoute("/ai-experiences")({
  component: TimelessPage,
  head: () =>
    pageHead(
      "AI Experiences",
      "FerryLore Timeless — cinematic historical experiences inspired by Harpers Ferry and historic places across Virginia, Maryland, and Washington, DC.",
    ),
});

const locations = ["Harpers Ferry", "Old Town Alexandria", "Georgetown", "Shenandoah"];
const periods = ["1860", "1920", "1944"];
const styles = ["Cinematic", "Wet plate", "Oil painting", "Editorial"];
const SESSION_CAP = 3;

async function fileToDataUrl(file: File): Promise<string> {
  const bitmap = await createImageBitmap(file);
  const max = 1024;
  const scale = Math.min(1, max / Math.max(bitmap.width, bitmap.height));
  const canvas = document.createElement("canvas");
  canvas.width = Math.max(1, Math.round(bitmap.width * scale));
  canvas.height = Math.max(1, Math.round(bitmap.height * scale));
  const ctx = canvas.getContext("2d");
  if (!ctx) throw new Error("Could not read that photograph.");
  ctx.drawImage(bitmap, 0, 0, canvas.width, canvas.height);
  bitmap.close();
  return canvas.toDataURL("image/jpeg", 0.86);
}

function usedCount() {
  try {
    return Number(sessionStorage.getItem("ferrylore-timeless-uses") || "0");
  } catch {
    return 0;
  }
}

function bumpCount() {
  try {
    sessionStorage.setItem("ferrylore-timeless-uses", String(usedCount() + 1));
  } catch {
    /* ignore */
  }
}

function TimelessPage() {
  const [location, setLocation] = useState("Harpers Ferry");
  const [period, setPeriod] = useState("1860");
  const [style, setStyle] = useState("Cinematic");
  const [preview, setPreview] = useState<string | null>(null);
  const [dataUrl, setDataUrl] = useState<string | null>(null);
  const [pastUrl, setPastUrl] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [ready, setReady] = useState(false);

  async function onFile(file: File | undefined) {
    setError(null);
    setReady(false);
    setPastUrl(null);
    if (!file) {
      setPreview(null);
      setDataUrl(null);
      return;
    }
    try {
      const url = await fileToDataUrl(file);
      setDataUrl(url);
      setPreview(url);
    } catch {
      setError("We couldn’t read that photograph. Try a JPG or PNG.");
    }
  }

  async function run() {
    setError(null);
    if (!dataUrl) {
      setError("Upload a photograph first — that’s whose face we keep.");
      return;
    }
    if (usedCount() >= SESSION_CAP) {
      setError("You’ve opened the past a few times this visit. Book a session and we’ll make the full film.");
      return;
    }
    setBusy(true);
    setReady(false);
    setPastUrl(null);
    try {
      const result = await enterThePast({
        data: { imageDataUrl: dataUrl, location, period, style },
      });
      if (!result.ok) {
        setError(result.error);
        return;
      }
      bumpCount();
      setPastUrl(result.pastUrl);
      setReady(true);
    } catch {
      setError("We couldn’t open the past from that photograph. Please try another image.");
    } finally {
      setBusy(false);
    }
  }

  return (
    <main id="main">
      <PageHero
        kicker="FerryLore Timeless"
        title="The past isn’t just something you read about. Step into it."
        lede="What if you could experience another time — and remain the hero of the story?"
        image="/images/couple-1860.jpg"
        video="/videos/timeless-walk.mp4"
        primary={{ label: "Enter the past", to: "/book" }}
      />
      <section className="bg-ink py-24">
        <Container>
          <div className="grid items-center gap-12 lg:grid-cols-2">
            <Reveal>
              <Kicker>Today · then</Kicker>
              <h2 className="font-serif text-4xl sm:text-5xl">
                Same people. Same overlook. A different century.
              </h2>
              <p className="mt-5 text-muted">
                Drag to move between now and 1860. Clothing changes. The place changes. The faces stay.
                Historical recreations are interpretations — never presented as documentary fact.
              </p>
            </Reveal>
            <Reveal>
              <BeforeAfter
                before="/images/couple-today.jpg"
                after="/images/couple-1860.jpg"
              />
            </Reveal>
          </div>

          <div className="mt-24">
            <Reveal>
              <Kicker>A film</Kicker>
              <h2 className="font-serif text-4xl sm:text-5xl">The still, set in motion.</h2>
              <p className="mt-4 max-w-xl text-muted">
                A photograph keeps a moment. A film lets you walk it.
              </p>
            </Reveal>
            <div className="relative mt-10 aspect-[16/9] overflow-hidden rounded-xl bg-ink-elevated">
              <video
                className="h-full w-full object-cover"
                src="/videos/timeless-walk.mp4"
                poster="/images/couple-1860-story.jpg"
                autoPlay
                muted
                loop
                playsInline
                controls
              />
            </div>
          </div>

          <div className="mt-24 rounded-xl border border-line bg-ink-soft p-6 sm:p-10">
            <h2 className="font-serif text-3xl sm:text-4xl">Place yourself in another time.</h2>
            <p className="mt-3 max-w-2xl text-muted">
              Upload a photograph. We’ll keep that face and stand them in {location}, {period},
              dressed for the year.
            </p>
            <div className="mt-8 grid gap-5 md:grid-cols-3">
              <Field label="Location">
                <Select value={location} onChange={(e) => setLocation(e.target.value)}>
                  {locations.map((l) => (
                    <option key={l}>{l}</option>
                  ))}
                </Select>
              </Field>
              <Field label="Time period">
                <Select value={period} onChange={(e) => setPeriod(e.target.value)}>
                  {periods.map((l) => (
                    <option key={l}>{l}</option>
                  ))}
                </Select>
              </Field>
              <Field label="Style">
                <Select value={style} onChange={(e) => setStyle(e.target.value)}>
                  {styles.map((l) => (
                    <option key={l}>{l}</option>
                  ))}
                </Select>
              </Field>
            </div>
            <div className="mt-6">
              <Field label="Upload a photograph">
                <input
                  type="file"
                  accept="image/jpeg,image/png,image/webp"
                  className="block w-full text-sm text-muted file:mr-4 file:rounded-full file:border-0 file:bg-ivory file:px-4 file:py-2 file:text-ink"
                  onChange={(e) => void onFile(e.target.files?.[0])}
                />
              </Field>
              {preview ? (
                <img
                  src={preview}
                  alt="Your photograph"
                  className="mt-4 aspect-[3/4] w-24 rounded-md object-cover object-[center_18%]"
                />
              ) : null}
            </div>
            <div className="mt-8 flex flex-wrap items-center gap-4">
              <Button onClick={() => void run()} disabled={busy}>
                {busy ? "Opening the past…" : "Create the experience"}
              </Button>
              {error ? <p className="text-sm text-beige">{error}</p> : null}
            </div>

            {ready && pastUrl && preview ? (
              <div className="mt-10 max-w-md">
                <BeforeAfter
                  before={preview}
                  after={pastUrl}
                  beforeLabel="Today"
                  afterLabel={`${location} · ${period}`}
                />
                <p className="mt-4 text-sm text-muted">
                  An interpretation, not a document. You remain the hero of the story.
                </p>
              </div>
            ) : null}
          </div>
        </Container>
      </section>
      <FinalCta title="Enter the past with FerryLore Timeless." />
    </main>
  );
}
