import React from "react";
import {AbsoluteFill, useCurrentFrame, interpolate, spring, useVideoConfig} from "remotion";
import {loadFont as loadBesley} from "@remotion/google-fonts/Besley";
import {loadFont as loadInter} from "@remotion/google-fonts/Inter";

const besley = loadBesley().fontFamily;
const inter = loadInter().fontFamily;

const PETROL = "#20383A";
const PETROL2 = "#0e1d1f";
const LIME = "#94c11f";
const LIME_D = "#6f9216";
const TEAL = "#298294";
const TEALL = "#9bd0d6";
const PAPER = "#f4f1ea";
const INK = "#20383A";
const RED = "#c0492f";
const AMBER = "#c2901c";

const reveal = (f: number, start: number) => ({
  opacity: interpolate(f, [start, start + 9], [0, 1], {extrapolateLeft: "clamp", extrapolateRight: "clamp"}),
  transform: `translateY(${interpolate(f, [start, start + 12], [16, 0], {extrapolateLeft: "clamp", extrapolateRight: "clamp"})}px)`,
});
const fade = (f: number, s: number, e: number, d = 12) =>
  interpolate(f, [s, s + d, e - d, e], [0, 1, 1, 0], {extrapolateLeft: "clamp", extrapolateRight: "clamp"});

// ---------- chat bubble ----------
const Bubble: React.FC<{side: "user" | "ai"; f: number; at: number; children: React.ReactNode}> = ({side, f, at, children}) => (
  <div
    style={{
      alignSelf: side === "user" ? "flex-end" : "flex-start",
      maxWidth: "88%",
      background: side === "user" ? TEAL : "#ffffff",
      color: side === "user" ? "#fff" : INK,
      borderRadius: 18,
      borderTopRightRadius: side === "user" ? 5 : 18,
      borderTopLeftRadius: side === "ai" ? 5 : 18,
      padding: "20px 26px",
      fontFamily: inter,
      fontSize: 30,
      lineHeight: 1.46,
      boxShadow: "0 5px 18px rgba(0,0,0,.10)",
      ...reveal(f, at),
    }}
  >
    {children}
  </div>
);

const Dots: React.FC<{f: number; at: number}> = ({f, at}) => (
  <div style={{alignSelf: "flex-start", background: "#fff", borderRadius: 18, borderTopLeftRadius: 5, padding: "22px 26px", display: "flex", gap: 9, boxShadow: "0 5px 18px rgba(0,0,0,.10)", ...reveal(f, at)}}>
    {[0, 1, 2].map((i) => {
      const o = 0.25 + 0.75 * (0.5 + 0.5 * Math.sin(((f - at) / 7 + i * 0.5) * Math.PI * 2));
      return <span key={i} style={{width: 15, height: 15, borderRadius: 99, background: "#9aa6a1", opacity: o}} />;
    })}
  </div>
);

// ---------- checklist item ----------
type ItemDef = {label: string; appear: number; green?: number; red?: number; phase: string};
const Check: React.FC<{f: number; it: ItemDef}> = ({f, it}) => {
  if (f < it.appear) return null;
  let state: "pending" | "red" | "green" = "pending";
  if (it.red && f >= it.red && (!it.green || f < it.green)) state = "red";
  if (it.green && f >= it.green) state = "green";
  const change = state === "green" ? it.green! : state === "red" ? it.red! : it.appear;
  const pop = interpolate(f, [change, change + 7], [0.55, 1], {extrapolateLeft: "clamp", extrapolateRight: "clamp"});
  const flagPulse = state === "red" ? 1 + 0.06 * Math.sin((f - it.red!) / 5) : 1;
  const box = state === "green" ? LIME_D : state === "red" ? RED : "transparent";
  const bord = state === "pending" ? "2px solid #b9c2bd" : "none";
  return (
    <div style={{display: "flex", alignItems: "center", gap: 16, margin: "16px 0", transform: `scale(${state === "red" ? flagPulse : 1})`, ...reveal(f, it.appear)}}>
      <div style={{width: 38, height: 38, borderRadius: 9, background: box, border: bord, display: "flex", alignItems: "center", justifyContent: "center", color: "#fff", fontSize: 26, fontWeight: 700, transform: `scale(${pop})`, flex: "none", boxShadow: state === "red" ? `0 0 0 5px rgba(192,73,60,.18)` : "none"}}>
        {state === "green" ? "✓" : state === "red" ? "✕" : ""}
      </div>
      <div style={{fontFamily: inter, fontSize: 27, color: state === "red" ? RED : state === "green" ? INK : "#65706b", fontWeight: state === "pending" ? 400 : 600}}>
        {it.label}
        {state === "red" && <span style={{color: RED, fontWeight: 700}}> — caught</span>}
      </div>
    </div>
  );
};

const PRE: ItemDef[] = [
  {phase: "pre", label: "Approved tool", appear: 110, green: 130},
  {phase: "pre", label: "No confidential data", appear: 150, green: 170},
  {phase: "pre", label: "Role, audience & format", appear: 190, green: 210},
  {phase: "pre", label: "Source notes attached", appear: 230, green: 250},
];
const POST: ItemDef[] = [
  {phase: "post", label: "Draft produced", appear: 470, green: 490},
  {phase: "post", label: "Every number verified", appear: 520, red: 560, green: 880},
  {phase: "post", label: "Sounds like us", appear: 940, red: 980, green: 1280},
  {phase: "post", label: "Nothing internal leaked", appear: 1300, green: 1320},
  {phase: "post", label: "Would I put my name on it?", appear: 1360, green: 1390},
];

export const Demo: React.FC = () => {
  const f = useCurrentFrame();
  const {fps} = useVideoConfig();

  const introO = fade(f, 0, 92, 14);
  const splitO = interpolate(f, [92, 112, 1470, 1495], [0, 1, 1, 0], {extrapolateLeft: "clamp", extrapolateRight: "clamp"});
  const closeO = fade(f, 1490, 1850, 18);
  const closeS = spring({frame: f - 1490, fps, config: {damping: 200}});

  return (
    <AbsoluteFill style={{fontFamily: inter, background: `radial-gradient(130% 130% at 82% 8%, #2c5054 0%, ${PETROL} 48%, ${PETROL2} 100%)`}}>
      <div style={{position: "absolute", top: 42, left: 56, fontFamily: besley, fontWeight: 700, fontSize: 32, color: "#f5f2ec", opacity: 0.9, zIndex: 5}}>
        PHINEO<span style={{color: LIME}}>.</span>
      </div>

      {/* INTRO */}
      {f < 110 && (
        <AbsoluteFill style={{justifyContent: "center", alignItems: "flex-start", padding: "0 130px", opacity: introO}}>
          <div style={{fontWeight: 700, letterSpacing: 6, fontSize: 26, color: TEALL, textTransform: "uppercase"}}>Live demo</div>
          <div style={{fontFamily: besley, fontWeight: 700, fontSize: 100, color: "#f5f2ec", lineHeight: 1.04, marginTop: 18}}>
            The checklist<br />does the work.
          </div>
          <div style={{width: 150, height: 9, background: LIME, borderRadius: 3, margin: "32px 0 24px"}} />
          <div style={{fontFamily: besley, fontStyle: "italic", fontSize: 38, color: LIME}}>AI drafts. Your guardrails decide.</div>
        </AbsoluteFill>
      )}

      {/* SPLIT: chat + rail */}
      {f >= 92 && f < 1495 && (
        <AbsoluteFill style={{flexDirection: "row", opacity: splitO, padding: "118px 56px 56px"}}>
          {/* chat */}
          <div style={{flex: 1, display: "flex", flexDirection: "column", justifyContent: "flex-end", gap: 18, overflow: "hidden", paddingRight: 44}}>
            {f >= 300 && (
              <div style={{alignSelf: "center", background: "rgba(255,255,255,.12)", color: TEALL, fontSize: 22, padding: "8px 18px", borderRadius: 99, ...reveal(f, 300)}}>
                Pre-flight done — we check before we type.
              </div>
            )}
            {f >= 350 && <Bubble side="user" f={f} at={350}>Draft a CSRD impact paragraph from these notes — concise and factual.</Bubble>}
            {f >= 410 && f < 450 && <Dots f={f} at={410} />}
            {f >= 450 && (
              <Bubble side="ai" f={f} at={450}>
                Our flagship programme delivered transformational impact, reaching{" "}
                <Num f={f} red={560}>4,200</Num> beneficiaries and dramatically improving lives across the community.
              </Bubble>
            )}
            {f >= 680 && <Bubble side="user" f={f} at={680}>You invented 4,200 — I never gave that figure. Use only my numbers; mark any gap as [figure needed].</Bubble>}
            {f >= 740 && f < 780 && <Dots f={f} at={740} />}
            {f >= 780 && <Bubble side="ai" f={f} at={780}>The programme reached <b style={{color: AMBER}}>[figure needed]</b> participants and improved their access to digital skills.</Bubble>}
            {f >= 1040 && <Bubble side="user" f={f} at={1040}>Now rewrite in our cautious, factual house tone — no superlatives, only what we can evidence.</Bubble>}
            {f >= 1100 && f < 1140 && <Dots f={f} at={1100} />}
            {f >= 1140 && (
              <Bubble side="ai" f={f} at={1140}>
                In 2025 the programme supported participants in building digital skills; final reach figures are pending verification from our monitoring data.
                <span style={{display: "inline-block", marginLeft: 8, color: LIME_D, fontWeight: 700}}>✓ ready to sign</span>
              </Bubble>
            )}
          </div>

          {/* rail — the hero */}
          <div style={{width: 640, background: "#fbfaf7", borderRadius: 20, padding: "30px 34px", boxShadow: "0 30px 70px rgba(0,0,0,.35)", alignSelf: "stretch", display: "flex", flexDirection: "column"}}>
            <div style={{fontFamily: besley, fontWeight: 700, fontSize: 36, color: PETROL}}>Your guardrails</div>
            <div style={{fontFamily: inter, fontSize: 22, color: LIME_D, fontWeight: 600, marginBottom: 8}}>the part WE bring — not the AI</div>
            <div style={{fontFamily: inter, fontSize: 20, letterSpacing: 2, color: TEAL, textTransform: "uppercase", fontWeight: 700, marginTop: 18}}>Pre-flight</div>
            {PRE.map((it, i) => <Check key={i} f={f} it={it} />)}
            <div style={{fontFamily: inter, fontSize: 20, letterSpacing: 2, color: TEAL, textTransform: "uppercase", fontWeight: 700, marginTop: 18}}>Post-flight</div>
            {POST.map((it, i) => <Check key={i} f={f} it={it} />)}
          </div>
        </AbsoluteFill>
      )}

      {/* CLOSING */}
      {f >= 1485 && (
        <AbsoluteFill style={{justifyContent: "center", alignItems: "center", opacity: closeO}}>
          <div style={{textAlign: "center", maxWidth: 1500, transform: `scale(${0.94 + 0.06 * closeS})`}}>
            <div style={{fontFamily: besley, fontWeight: 700, fontSize: 70, color: "#f5f2ec", lineHeight: 1.15}}>
              The first answer was confident — and wrong.<br />The third, you could sign.
            </div>
            <div style={{width: 160, height: 9, background: LIME, borderRadius: 3, margin: "40px auto 30px"}} />
            <div style={{fontFamily: inter, fontSize: 40, color: TEALL}}>The difference wasn't the AI — it was the checklist.</div>
            <div style={{fontFamily: besley, fontStyle: "italic", fontSize: 48, color: "#f5f2ec", marginTop: 24}}>AI advises — you decide and you sign.</div>
          </div>
        </AbsoluteFill>
      )}
    </AbsoluteFill>
  );
};

// highlighted invented number inside a bubble
const Num: React.FC<{f: number; red: number; children: React.ReactNode}> = ({f, red, children}) => {
  const hl = interpolate(f, [red, red + 20], [0, 1], {extrapolateLeft: "clamp", extrapolateRight: "clamp"});
  return (
    <span style={{background: `rgba(192,73,60,${0.2 * hl})`, color: hl > 0.3 ? RED : INK, fontWeight: hl > 0.3 ? 700 : 400, borderBottom: hl > 0.5 ? `3px solid ${RED}` : "none", padding: "0 4px", borderRadius: 4}}>
      {children}
    </span>
  );
};
