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 GREY = "#8a938f";

const reveal = (f: number, s: number) => ({
  opacity: interpolate(f, [s, s + 9], [0, 1], {extrapolateLeft: "clamp", extrapolateRight: "clamp"}),
  transform: `translateY(${interpolate(f, [s, s + 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"});
const win = (f: number, a: number, b: number) => interpolate(f, [a, a + 14, b - 14, b], [0, 1, 1, 0], {extrapolateLeft: "clamp", extrapolateRight: "clamp"});
const app = (f: number, a: number) => interpolate(f, [a, a + 12], [0, 1], {extrapolateLeft: "clamp", extrapolateRight: "clamp"});

// ---------- chat ----------
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>
);
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>;
};

// ---------- checklist rail ----------
type ItemDef = {label: string; appear: number; green?: number; red?: number};
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 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: "15px 0", ...reveal(f, it.appear)}}>
      <div style={{width: 36, height: 36, borderRadius: 9, background: box, border: bord, display: "flex", alignItems: "center", justifyContent: "center", color: "#fff", fontSize: 25, 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: 26, 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[] = [
  {label: "Approved tool", appear: 118, green: 240},
  {label: "No confidential data", appear: 268, green: 390},
  {label: "Role, audience, format", appear: 418, green: 505},
  {label: "Source attached", appear: 532, green: 622},
];
const POST: ItemDef[] = [
  {label: "Draft produced", appear: 832, green: 854},
  {label: "Every number verified", appear: 884, red: 928, green: 1250},
  {label: "Sounds like us", appear: 1305, red: 1345, green: 1650},
  {label: "Nothing internal leaked", appear: 1670, green: 1692},
  {label: "Would I put my name on it?", appear: 1730, green: 1760},
];

// ---------- pre-flight visuals (left) ----------
const Caption: React.FC<{children: React.ReactNode}> = ({children}) => (
  <div style={{fontFamily: besley, fontWeight: 700, fontSize: 38, color: "#f5f2ec", marginBottom: 26}}>{children}</div>
);
const card: React.CSSProperties = {background: "#fbfaf7", borderRadius: 16, padding: "26px 30px", boxShadow: "0 20px 60px rgba(0,0,0,.3)", width: 760};

const VTool: React.FC<{f: number}> = ({f}) => {
  const rows = [
    {t: "ChatGPT — free, personal login", ok: false, at: 130},
    {t: "Your private Claude account", ok: false, at: 152},
    {t: "Microsoft Copilot — company · EU-hosted", ok: true, at: 176},
  ];
  return (
    <div>
      <Caption>1 · The right tool for this data?</Caption>
      <div style={card}>
        {rows.map((r, i) => {
          const markF = r.at + 40;
          const m = app(f, markF);
          return (
            <div key={i} style={{display: "flex", alignItems: "center", justifyContent: "space-between", gap: 18, padding: "14px 16px", margin: "8px 0", borderRadius: 10, border: r.ok ? `2px solid ${LIME_D}` : "2px solid #e6e1d6", background: r.ok ? `rgba(111,146,22,${0.08 * m})` : "#fff", ...reveal(f, r.at)}}>
              <span style={{fontFamily: inter, fontSize: 25, color: r.ok ? INK : "#9a9a90", textDecoration: !r.ok && m > 0.4 ? "line-through" : "none", fontWeight: r.ok ? 700 : 400}}>{r.t}</span>
              <span style={{width: 34, height: 34, borderRadius: 8, flex: "none", display: "flex", alignItems: "center", justifyContent: "center", color: "#fff", fontWeight: 700, fontSize: 21, background: r.ok ? LIME_D : RED, opacity: m}}>{r.ok ? "✓" : "✕"}</span>
            </div>
          );
        })}
      </div>
    </div>
  );
};

const Field: React.FC<{f: number; label: string; value: string; maskAt?: number; keep?: boolean}> = ({f, label, value, maskAt, keep}) => {
  const m = maskAt ? app(f, maskAt) : 0;
  return (
    <div style={{display: "flex", alignItems: "center", gap: 20, padding: "13px 0", borderBottom: "1px solid #eee7da"}}>
      <span style={{fontFamily: inter, fontSize: 21, color: GREY, width: 180, textTransform: "uppercase", letterSpacing: 1, fontWeight: 600}}>{label}</span>
      <span style={{flex: 1, position: "relative", fontFamily: inter, fontSize: 26, color: INK, fontWeight: 600}}>
        <span style={{opacity: keep ? 1 : 1 - m}}>{value}</span>
        {!keep && <span style={{position: "absolute", left: 0, opacity: m, color: PETROL, letterSpacing: 3}}>•••••••••</span>}
      </span>
      {keep ? <span style={{fontSize: 20, color: LIME_D, fontWeight: 700}}>keep</span> : <span style={{fontSize: 19, color: LIME_D, fontWeight: 700, opacity: m, border: `1px solid ${LIME_D}`, borderRadius: 99, padding: "3px 12px"}}>anonymised</span>}
    </div>
  );
};
const VData: React.FC<{f: number}> = ({f}) => (
  <div>
    <Caption>2 · Stripped the sensitive bits?</Caption>
    <div style={card}>
      <Field f={f} label="Beneficiary" value="Maria Schmidt" maskAt={322} />
      <Field f={f} label="Budget" value="€480,000" maskAt={352} />
      <Field f={f} label="Partner org" value="Caritas Berlin" keep />
    </div>
  </div>
);

const VBrief: React.FC<{f: number}> = ({f}) => {
  const tags = [["Role", "a sceptical CFO", 430], ["Audience", "the board", 452], ["Format", "5 bullets", 474]] as const;
  return (
    <div>
      <Caption>3 · Briefed it properly?</Caption>
      <div style={{...card, display: "flex", flexWrap: "wrap", gap: 14}}>
        {tags.map(([k, v, at], i) => (
          <span key={i} style={{display: "inline-flex", gap: 8, alignItems: "baseline", padding: "12px 18px", borderRadius: 10, background: "#eef3e6", ...reveal(f, at as number)}}>
            <b style={{fontFamily: inter, fontSize: 19, color: TEAL, textTransform: "uppercase", letterSpacing: 1}}>{k}</b>
            <span style={{fontFamily: inter, fontSize: 25, color: INK, fontWeight: 600}}>{v}</span>
          </span>
        ))}
        <div style={{width: "100%", fontFamily: inter, fontSize: 22, color: GREY, marginTop: 6, ...reveal(f, 496)}}>A clear brief — not a vague ask.</div>
      </div>
    </div>
  );
};

const VSource: React.FC<{f: number}> = ({f}) => (
  <div>
    <Caption>4 · Gave it the source?</Caption>
    <div style={{...card, display: "flex", alignItems: "center", gap: 22}}>
      <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke={TEAL} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" style={{flex: "none"}}><path d="M21 11.5l-8.5 8.5a5 5 0 01-7-7l8.5-8.5a3.3 3.3 0 014.7 4.7L9 17.5a1.7 1.7 0 01-2.3-2.3L14 8" /></svg>
      <div style={{flex: 1}}>
        <div style={{fontFamily: inter, fontSize: 26, color: INK, fontWeight: 700}}>Q3-impact-notes.pdf</div>
        <div style={{fontFamily: inter, fontSize: 21, color: GREY, marginTop: 4}}>It reads your notes — it doesn't guess.</div>
      </div>
      <span style={{fontFamily: inter, fontSize: 21, color: LIME_D, fontWeight: 700, border: `1px solid ${LIME_D}`, borderRadius: 99, padding: "6px 16px", opacity: app(f, 614)}}>attached ✓</span>
    </div>
  </div>
);

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

  const introO = fade(f, 0, 92, 14);
  const splitO = interpolate(f, [92, 112, 1782, 1808], [0, 1, 1, 0], {extrapolateLeft: "clamp", extrapolateRight: "clamp"});
  const preMode = f < 655;
  const signO = interpolate(f, [1808, 1840, 2222, 2252], [0, 1, 1, 0], {extrapolateLeft: "clamp", extrapolateRight: "clamp"});
  const sigDraw = interpolate(f, [1945, 2020], [1400, 0], {extrapolateLeft: "clamp", extrapolateRight: "clamp"});
  const sent = f >= 2138;
  const closeO = fade(f, 2250, 2740, 18);
  const closeS = spring({frame: f - 2250, 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>

      {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>
      )}

      {f >= 92 && f < 1808 && (
        <AbsoluteFill style={{flexDirection: "row", opacity: splitO, padding: "118px 56px 56px"}}>
          {/* left: pre-flight visuals, then chat */}
          <div style={{flex: 1, display: "flex", flexDirection: "column", justifyContent: preMode ? "center" : "flex-end", gap: 18, overflow: "hidden", paddingRight: 44, position: "relative"}}>
            {preMode && (
              <div style={{position: "relative", height: 520}}>
                <div style={{position: "absolute", inset: 0, opacity: win(f, 112, 256)}}><VTool f={f} /></div>
                <div style={{position: "absolute", inset: 0, opacity: win(f, 268, 406)}}><VData f={f} /></div>
                <div style={{position: "absolute", inset: 0, opacity: win(f, 418, 520)}}><VBrief f={f} /></div>
                <div style={{position: "absolute", inset: 0, opacity: win(f, 532, 650)}}><VSource f={f} /></div>
              </div>
            )}
            {f >= 660 && f < 720 && <div style={{alignSelf: "center", background: "rgba(255,255,255,.12)", color: TEALL, fontSize: 22, padding: "8px 18px", borderRadius: 99, ...reveal(f, 660)}}>Pre-flight done — now we type.</div>}
            {f >= 715 && <Bubble side="user" f={f} at={715}>Draft a CSRD impact paragraph from these notes — concise and factual.</Bubble>}
            {f >= 770 && f < 810 && <Dots f={f} at={770} />}
            {f >= 814 && <Bubble side="ai" f={f} at={814}>Our flagship programme delivered transformational impact, reaching <Num f={f} red={928}>4,200</Num> beneficiaries and dramatically improving lives across the community.</Bubble>}
            {f >= 1040 && <Bubble side="user" f={f} at={1040}>You invented 4,200 — I never gave that figure. Use only my numbers; mark any gap as [figure needed].</Bubble>}
            {f >= 1100 && f < 1140 && <Dots f={f} at={1100} />}
            {f >= 1144 && <Bubble side="ai" f={f} at={1144}>The programme reached <b style={{color: AMBER}}>[figure needed]</b> participants and improved their access to digital skills.</Bubble>}
            {f >= 1395 && <Bubble side="user" f={f} at={1395}>Now rewrite in our cautious, factual house tone — no superlatives, only what we can evidence.</Bubble>}
            {f >= 1455 && f < 1495 && <Dots f={f} at={1455} />}
            {f >= 1499 && <Bubble side="ai" f={f} at={1499}>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>

          {/* right: rail */}
          <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: 14}}>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: 14}}>Post-flight</div>
            {POST.map((it, i) => <Check key={i} f={f} it={it} />)}
          </div>
        </AbsoluteFill>
      )}

      {/* SIGN & SEND */}
      {f >= 1805 && f < 2258 && (
        <AbsoluteFill style={{justifyContent: "center", alignItems: "center", opacity: signO}}>
          <div style={{width: 1180, background: "#fbfaf7", borderRadius: 20, boxShadow: "0 40px 90px rgba(0,0,0,.42)", padding: "44px 56px", ...reveal(f, 1840)}}>
            <div style={{display: "flex", justifyContent: "space-between", alignItems: "center"}}>
              <div style={{fontFamily: inter, fontSize: 22, letterSpacing: 2, textTransform: "uppercase", color: TEAL, fontWeight: 700}}>Final draft</div>
              <div style={{fontFamily: inter, fontSize: 22, color: LIME_D, fontWeight: 700, display: "flex", alignItems: "center", gap: 12}}><span style={{width: 26, height: 26, borderRadius: 8, background: LIME_D, color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 17}}>✓</span>Cleared by every check</div>
            </div>
            <div style={{fontFamily: inter, fontSize: 33, lineHeight: 1.5, color: INK, marginTop: 26}}>In 2025 the programme supported participants in building digital skills; final reach figures are pending verification from our monitoring data.</div>
            <div style={{height: 1, background: "#e3ded3", margin: "34px 0 24px"}} />
            <div style={{display: "flex", justifyContent: "space-between", alignItems: "flex-end"}}>
              <div>
                <div style={{fontFamily: inter, fontSize: 19, color: GREY, textTransform: "uppercase", letterSpacing: 2, fontWeight: 700, marginBottom: 2}}>Signed</div>
                <svg width="340" height="84" viewBox="0 0 340 84" fill="none"><path d="M12,58 C44,10 78,8 96,50 C108,78 132,80 150,48 C168,14 206,10 236,54 C252,78 286,68 332,26" stroke={INK} strokeWidth="4.5" strokeLinecap="round" strokeLinejoin="round" strokeDasharray="1400" strokeDashoffset={sigDraw} /></svg>
                <div style={{fontFamily: inter, fontSize: 21, color: INK, fontWeight: 600, opacity: app(f, 2038)}}>M. Köhler · CC Lead · 11 Jun 2026</div>
              </div>
              {f >= 2074 && (
                <div style={reveal(f, 2074)}>
                  {!sent ? (
                    <div style={{display: "flex", alignItems: "center", gap: 14, background: TEAL, color: "#fff", fontFamily: inter, fontWeight: 700, fontSize: 28, padding: "16px 34px", borderRadius: 14}}>Send<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 2L11 13" /><path d="M22 2l-7 20-4-9-9-4 20-7z" /></svg></div>
                  ) : (
                    <div style={{display: "flex", alignItems: "center", gap: 14, background: LIME_D, color: "#fff", fontFamily: inter, fontWeight: 700, fontSize: 28, padding: "16px 34px", borderRadius: 14, ...reveal(f, 2138)}}>Sent<span style={{fontSize: 24}}>✓</span></div>
                  )}
                </div>
              )}
            </div>
          </div>
          <div style={{fontFamily: besley, fontStyle: "italic", fontSize: 46, color: "#f5f2ec", marginTop: 50, opacity: app(f, 2178)}}>You decide. You sign. You send.</div>
        </AbsoluteFill>
      )}

      {/* CLOSING */}
      {f >= 2250 && (
        <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>
  );
};
