// brand.jsx — ShaqoSmart film toolkit (calm / premium / bilingual)
// Reusable motion primitives shared by all three videos.
// Requires animations.jsx (Sprite/useSprite/useTimeline/Easing/clamp/interpolate) loaded first.
// Exports to window at the bottom.

// ── Brand tokens ────────────────────────────────────────────────────────────
const C = {
  sand:   '#F6EEE0',
  paper:  '#FDFAF3',
  ink:    '#16110B',
  ink2:   '#4A4030',
  ink3:   '#877B66',
  green:  '#0F5C3F',
  green700:'#0B4630',
  green500:'#167551',
  greenTint:'#E4EDE5',
  gold:   '#C98A14',
  gold500:'#DDA02B',
  goldTint:'#F4E6C6',
  cream:  '#FBF6EC',
  border: '#E3D5BD',
  danger: '#B23A2E',
};
const FR   = "'Fraunces', Georgia, serif";        // display
const BODY = "'IBM Plex Sans', 'Noto Sans', system-ui, sans-serif"; // captions / UI
const MONO = "'IBM Plex Mono', ui-monospace, monospace";

// fade helper across a sprite window
function fadeOf(localTime, duration, inDur = 0.7, outDur = 0.7) {
  if (!isFinite(duration)) return localTime < inDur ? clamp(localTime / inDur, 0, 1) : 1;
  const a = inDur > 0 ? clamp(localTime / inDur, 0, 1) : 1;
  const b = outDur > 0 ? clamp((duration - localTime) / outDur, 0, 1) : 1;
  return Math.min(a, b);
}
const easeIO = (window.Easing || {}).easeInOutCubic || ((t) => t);
const easeOut = (window.Easing || {}).easeOutCubic || ((t) => t);

// ── Vignette + film grain wash (always-on, very subtle) ─────────────────────
function Vignette({ strength = 0.5 }) {
  return (
    <div style={{
      position: 'absolute', inset: 0, pointerEvents: 'none',
      boxShadow: `inset 0 0 220px rgba(10,8,4,${0.45 * strength}), inset 0 0 80px rgba(10,8,4,${0.18 * strength})`,
    }} />
  );
}

// ── PhotoScene — full-bleed photo, slow Ken Burns, color grade, legibility scrim
// grade: 'muted' (act 1) | 'warm' (act 2/3) | 'neutral'
function PhotoScene({
  src, grade = 'neutral',
  from = 1.04, to = 1.12, originX = 50, originY = 50,
  inDur = 0.9, outDur = 0.9,
  scrim = 'bottom', // 'bottom' | 'full' | 'none'
  brightness, fit = 'cover', bg = C.ink,
}) {
  const { localTime, duration } = useSprite();
  const op = fadeOf(localTime, duration, inDur, outDur);
  const p = isFinite(duration) && duration > 0 ? clamp(localTime / duration, 0, 1) : 0;
  const scale = from + (to - from) * p;

  const grades = {
    muted:   `saturate(0.46) brightness(${brightness ?? 0.84}) contrast(1.03)`,
    warm:    `saturate(1.06) brightness(${brightness ?? 1.02}) contrast(1.01)`,
    neutral: `saturate(0.96) brightness(${brightness ?? 0.96})`,
  };
  const tint = {
    muted: 'linear-gradient(180deg, rgba(18,26,34,0.30) 0%, rgba(14,20,28,0.12) 40%, rgba(10,8,4,0.10) 100%)',
    warm:  'linear-gradient(180deg, rgba(201,138,20,0.05) 0%, rgba(15,92,63,0.04) 60%, rgba(22,17,11,0.06) 100%)',
    neutral: 'none',
  }[grade];
  const legibility = scrim === 'none' ? 'none'
    : scrim === 'full'
      ? 'linear-gradient(180deg, rgba(22,17,11,0.34) 0%, rgba(22,17,11,0.10) 38%, rgba(22,17,11,0.66) 100%)'
      : 'linear-gradient(180deg, rgba(22,17,11,0) 42%, rgba(22,17,11,0.40) 74%, rgba(22,17,11,0.78) 100%)';

  return (
    <div style={{ position: 'absolute', inset: 0, opacity: op, overflow: 'hidden', background: bg }}>
      <img src={src} alt="" style={{
        position: 'absolute', inset: 0, width: '100%', height: '100%',
        objectFit: fit, objectPosition: `${originX}% ${originY}%`,
        transform: `scale(${scale})`, transformOrigin: `${originX}% ${originY}%`,
        filter: grades[grade], willChange: 'transform',
      }} />
      {tint !== 'none' && <div style={{ position: 'absolute', inset: 0, background: tint }} />}
      {legibility !== 'none' && <div style={{ position: 'absolute', inset: 0, background: legibility }} />}
      <Vignette strength={grade === 'muted' ? 0.7 : 0.42} />
    </div>
  );
}

// ── Solid color field (for turn / end cards) with faint motif lattice ───────
function ColorField({ bg = C.sand, motif = true, inDur = 0.6, outDur = 0.6 }) {
  const { localTime, duration } = useSprite();
  const op = fadeOf(localTime, duration, inDur, outDur);
  return (
    <div style={{ position: 'absolute', inset: 0, background: bg, opacity: op }}>
      {motif && <div style={{
        position: 'absolute', inset: 0, opacity: 0.5,
        backgroundImage: "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='44' height='44' viewBox='0 0 44 44'%3E%3Cpath d='M22 3L41 22L22 41L3 22Z' fill='none' stroke='%23C98A14' stroke-width='1' stroke-opacity='0.16'/%3E%3C/svg%3E\")",
        backgroundSize: '44px 44px',
      }} />}
      <Vignette strength={0.25} />
    </div>
  );
}

// ── Diamond motif band (thin gold rule) ─────────────────────────────────────
function MotifBand({ color = C.gold, width = 220, y = 0 }) {
  return (
    <div style={{
      height: 12, width,
      background: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='12' viewBox='0 0 24 12'%3E%3Cpath d='M12 1L23 6L12 11L1 6Z' fill='none' stroke='${encodeURIComponent(color)}' stroke-width='1.3'/%3E%3Ccircle cx='12' cy='6' r='1.3' fill='${encodeURIComponent(color)}'/%3E%3C/svg%3E") repeat-x center / 24px 12px`,
      marginTop: y,
    }} />
  );
}

// ── Bilingual subtitle bar (the VO-timed caption track) ─────────────────────
// Sits low; EN white IBM Plex semibold, SO gold italic beneath, on a soft ink bar.
function CaptionBar({ en, so, y = 902, maxWidth = 1280 }) {
  const { localTime, duration } = useSprite();
  const op = fadeOf(localTime, duration, 0.45, 0.45);
  const rise = (1 - easeOut(clamp(localTime / 0.5, 0, 1))) * 10;
  return (
    <div style={{
      position: 'absolute', left: '50%', top: y, transform: `translate(-50%, ${rise}px)`,
      opacity: op, maxWidth, width: 'max-content', textAlign: 'center',
      padding: '16px 30px', borderRadius: 16,
      background: 'rgba(18,13,8,0.60)', backdropFilter: 'blur(8px)',
      WebkitBackdropFilter: 'blur(8px)', boxShadow: '0 10px 34px rgba(0,0,0,0.28)',
    }}>
      <div style={{
        fontFamily: BODY, fontWeight: 600, fontSize: 32, lineHeight: 1.22,
        color: '#FFFFFF', letterSpacing: '-0.005em', whiteSpace: 'nowrap',
        textShadow: '0 1px 2px rgba(0,0,0,0.35)',
      }}>{en}</div>
      {so && <div style={{
        fontFamily: BODY, fontStyle: 'italic', fontWeight: 400, fontSize: 23,
        lineHeight: 1.3, color: C.gold500, marginTop: 7, letterSpacing: '0.01em', whiteSpace: 'nowrap',
      }}>{so}</div>}
    </div>
  );
}

// ── Eyebrow / character label (top-left lower-third kicker) ──────────────────
function Kicker({ label, sub, x = 96, y = 120, color = C.cream, dark = false }) {
  const { localTime, duration } = useSprite();
  const op = fadeOf(localTime, duration, 0.5, 0.5);
  const dx = (1 - easeOut(clamp(localTime / 0.6, 0, 1))) * -14;
  return (
    <div style={{ position: 'absolute', left: x, top: y, opacity: op, transform: `translateX(${dx}px)` }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <span style={{ width: 10, height: 10, transform: 'rotate(45deg)', background: C.gold, borderRadius: 1, display: 'block' }} />
        <span style={{ fontFamily: BODY, fontWeight: 600, fontSize: 16, letterSpacing: '0.18em', textTransform: 'uppercase', color: dark ? C.green : C.gold }}>{label}</span>
      </div>
      {sub && <div style={{ fontFamily: FR, fontWeight: 600, fontSize: 30, color: dark ? C.ink : color, marginTop: 10, letterSpacing: '-0.01em' }}>{sub}</div>}
    </div>
  );
}

// ── Big on-screen headline (Fraunces) — for stat / statement moments ────────
function Headline({ lines = [], x = 96, y = 360, size = 78, color = C.cream, align = 'left', accentIndex = -1, accent = C.gold, maxWidth = 1100 }) {
  const { localTime, duration } = useSprite();
  const op = fadeOf(localTime, duration, 0.6, 0.6);
  return (
    <div style={{ position: 'absolute', left: x, top: y, opacity: op, textAlign: align, maxWidth,
      transform: align === 'center' ? 'translateX(-50%)' : 'none' }}>
      {lines.map((ln, i) => {
        const t = clamp((localTime - 0.12 * i) / 0.6, 0, 1);
        const e = easeOut(t);
        return (
          <div key={i} style={{
            fontFamily: FR, fontWeight: 800, fontSize: size, lineHeight: 1.04,
            letterSpacing: '-0.02em', color: i === accentIndex ? accent : color,
            opacity: e, transform: `translateY(${(1 - e) * 18}px)`,
            textShadow: color === C.cream ? '0 2px 14px rgba(0,0,0,0.28)' : 'none',
          }}>{ln}</div>
        );
      })}
    </div>
  );
}

// ── Count-up stat (big number that ticks 0 → value) ─────────────────────────
function StatCounter({ to = 100, suffix = '%', label, sub, x = 96, y = 300, size = 150, color = C.gold, labelColor = C.cream, align = 'left', decimals = 0, separator = false }) {
  const { localTime, duration } = useSprite();
  const op = fadeOf(localTime, duration, 0.5, 0.6);
  const t = easeOut(clamp(localTime / Math.min(1.6, (isFinite(duration) ? duration * 0.6 : 1.6)), 0, 1));
  let val = to * t;
  let shown = decimals > 0 ? val.toFixed(decimals) : String(Math.round(val));
  if (separator) shown = Number(shown).toLocaleString('en-US');
  return (
    <div style={{ position: 'absolute', left: x, top: y, opacity: op, textAlign: align,
      transform: align === 'center' ? 'translateX(-50%)' : 'none' }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: align === 'center' ? 'center' : 'flex-start' }}>
        <span style={{ fontFamily: FR, fontWeight: 800, fontSize: size, lineHeight: 0.9, color, letterSpacing: '-0.03em', fontVariantNumeric: 'tabular-nums' }}>{shown}</span>
        {suffix && <span style={{ fontFamily: FR, fontWeight: 700, fontSize: size * 0.46, color, marginLeft: 6 }}>{suffix}</span>}
      </div>
      {label && <div style={{ fontFamily: BODY, fontWeight: 600, fontSize: 30, color: labelColor, marginTop: 16, maxWidth: 760, lineHeight: 1.25, textShadow: '0 1px 8px rgba(0,0,0,0.25)' }}>{label}</div>}
      {sub && <div style={{ fontFamily: BODY, fontWeight: 400, fontSize: 17, color: C.ink3, marginTop: 10, letterSpacing: '0.02em' }}>{sub}</div>}
    </div>
  );
}

// ── Logo mark (green tile + cream S + gold dot) ─────────────────────────────
function LogoMark({ size = 96, build = 1 }) {
  const r = size * 0.28;
  const dot = size * 0.2;
  return (
    <div style={{ position: 'relative', width: size, height: size, flex: '0 0 auto' }}>
      <div style={{
        position: 'absolute', inset: 0, borderRadius: r,
        background: `linear-gradient(150deg, ${C.green500} 0%, ${C.green} 55%, ${C.green700} 100%)`,
        boxShadow: '0 10px 30px rgba(15,92,63,0.34)',
        transform: `scale(${0.7 + 0.3 * build})`, opacity: build,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <span style={{ fontFamily: FR, fontWeight: 700, fontSize: size * 0.62, color: C.cream, lineHeight: 1, marginTop: size * 0.02 }}>S</span>
      </div>
      <div style={{
        position: 'absolute', top: -dot * 0.18, right: -dot * 0.12, width: dot, height: dot, borderRadius: '50%',
        background: C.gold, border: `${size * 0.03}px solid ${C.sand}`,
        transform: `scale(${build})`, opacity: build,
      }} />
    </div>
  );
}

// ── Wordmark "ShaqoSmart" (Smart in gold) ───────────────────────────────────
function Wordmark({ size = 64, color = C.ink, reveal = 1 }) {
  return (
    <span style={{ fontFamily: FR, fontWeight: 700, fontSize: size, letterSpacing: '-0.02em', color, lineHeight: 1, whiteSpace: 'nowrap',
      display: 'inline-block', opacity: reveal, transform: `translateX(${(1 - reveal) * -24}px)` }}>
      Shaqo<span style={{ color: C.gold }}>Smart</span>
    </span>
  );
}

// ── Logo lockup (mark + wordmark), horizontal ───────────────────────────────
function LogoLockup({ size = 88, gap = 22, color = C.ink, build = 1, reveal = 1 }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap }}>
      <LogoMark size={size} build={build} />
      <Wordmark size={size * 0.74} color={color} reveal={reveal} />
    </div>
  );
}

// ── Circular match ring (e.g. 84%) with count-up ────────────────────────────
function MatchRing({ value = 84, size = 220, x, y, color = C.green, track = '#E3D5BD', label = 'match', delay = 0, thickness = 16 }) {
  const { localTime } = useSprite();
  const t = easeOut(clamp((localTime - delay) / 1.4, 0, 1));
  const shown = Math.round(value * t);
  const R = (size - thickness) / 2;
  const circ = 2 * Math.PI * R;
  const off = circ * (1 - (value / 100) * t);
  const wrap = (x != null) ? { position: 'absolute', left: x, top: y } : { position: 'relative' };
  return (
    <div style={{ ...wrap, width: size, height: size }}>
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ transform: 'rotate(-90deg)' }}>
        <circle cx={size / 2} cy={size / 2} r={R} fill="none" stroke={track} strokeWidth={thickness} />
        <circle cx={size / 2} cy={size / 2} r={R} fill="none" stroke={color} strokeWidth={thickness}
          strokeLinecap="round" strokeDasharray={circ} strokeDashoffset={off} />
      </svg>
      <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
        <span style={{ fontFamily: FR, fontWeight: 800, fontSize: size * 0.30, color: C.ink, letterSpacing: '-0.02em', lineHeight: 1 }}>{shown}<span style={{ fontSize: size * 0.16 }}>%</span></span>
        <span style={{ fontFamily: BODY, fontWeight: 600, fontSize: size * 0.075, letterSpacing: '0.16em', textTransform: 'uppercase', color: C.ink3, marginTop: 6 }}>{label}</span>
      </div>
    </div>
  );
}

// ── Browser / app frame (warm UI card) ──────────────────────────────────────
function AppFrame({ x, y, width = 940, height = 600, title = 'shaqosmart.com', children, lift = 1, pad = true }) {
  return (
    <div style={{
      position: 'absolute', left: x, top: y, width, height,
      background: C.paper, borderRadius: 22, overflow: 'hidden',
      border: `1px solid ${C.border}`,
      boxShadow: `0 ${30 * lift}px ${70 * lift}px rgba(45,32,12,0.22), 0 8px 20px rgba(45,32,12,0.12)`,
      transform: `translateY(${(1 - lift) * 26}px)`,
      display: 'flex', flexDirection: 'column',
    }}>
      <div style={{ height: 46, flex: '0 0 auto', background: C.sand, borderBottom: `1px solid ${C.border}`, display: 'flex', alignItems: 'center', padding: '0 18px', gap: 8 }}>
        <span style={{ width: 11, height: 11, borderRadius: '50%', background: '#E0B6A8' }} />
        <span style={{ width: 11, height: 11, borderRadius: '50%', background: '#E8D29A' }} />
        <span style={{ width: 11, height: 11, borderRadius: '50%', background: '#C5D8C8' }} />
        <div style={{ flex: 1, display: 'flex', justifyContent: 'center' }}>
          <div style={{ fontFamily: MONO, fontSize: 14, color: C.ink3, background: C.paper, border: `1px solid ${C.border}`, borderRadius: 8, padding: '4px 18px' }}>{title}</div>
        </div>
        <span style={{ width: 60 }} />
      </div>
      <div style={{ flex: 1, position: 'relative', padding: pad ? 28 : 0, overflow: 'hidden' }}>{children}</div>
    </div>
  );
}

// ── Checklist row (compliance) ──────────────────────────────────────────────
function CheckRow({ label, status = 'ok', appear = 1 }) {
  const map = {
    ok:      { bg: C.greenTint, br: '#C5D8C8', fg: C.green, icon: '✓', tag: 'Verified' },
    missing: { bg: C.danger + '14', br: '#E7C3BC', fg: C.danger, icon: '!', tag: 'Missing' },
    fixed:   { bg: C.greenTint, br: '#C5D8C8', fg: C.green, icon: '✓', tag: 'Added' },
  }[status];
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 16, padding: '16px 20px',
      background: C.paper, border: `1px solid ${C.border}`, borderRadius: 14, marginBottom: 12,
      opacity: appear, transform: `translateX(${(1 - appear) * 16}px)`,
    }}>
      <span style={{ width: 34, height: 34, borderRadius: 10, background: map.bg, border: `1px solid ${map.br}`, color: map.fg, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: BODY, fontWeight: 700, fontSize: 18, flex: '0 0 auto' }}>{map.icon}</span>
      <span style={{ fontFamily: BODY, fontWeight: 500, fontSize: 21, color: C.ink, flex: 1 }}>{label}</span>
      <span style={{ fontFamily: BODY, fontWeight: 600, fontSize: 14, letterSpacing: '0.08em', textTransform: 'uppercase', color: map.fg }}>{map.tag}</span>
    </div>
  );
}

// ── Skill chip ──────────────────────────────────────────────────────────────
function Chip({ children, tone = 'gold', appear = 1 }) {
  const t = tone === 'gold' ? { bg: C.goldTint, br: '#E8D29A', fg: '#8A5E0C' } : { bg: C.greenTint, br: '#C5D8C8', fg: C.green };
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, padding: '9px 16px', borderRadius: 999, background: t.bg, border: `1px solid ${t.br}`, color: t.fg, fontFamily: BODY, fontWeight: 600, fontSize: 18, whiteSpace: 'nowrap', opacity: appear, transform: `scale(${0.85 + 0.15 * appear})` }}>{children}</span>
  );
}

// ── EN/SO language toggle pill ──────────────────────────────────────────────
function LangToggle({ active = 'EN', x, y, scale = 1 }) {
  const wrap = (x != null) ? { position: 'absolute', left: x, top: y } : {};
  const opt = (k) => ({
    padding: '10px 22px', borderRadius: 999, fontFamily: BODY, fontWeight: 700, fontSize: 20,
    background: active === k ? C.green : 'transparent', color: active === k ? C.cream : C.ink3,
    transition: 'all .3s',
  });
  return (
    <div style={{ ...wrap, transform: `scale(${scale})`, display: 'inline-flex', padding: 5, borderRadius: 999, background: C.sand, border: `1px solid ${C.border}`, gap: 4 }}>
      <span style={opt('EN')}>EN</span>
      <span style={opt('SO')}>SO</span>
    </div>
  );
}

// ── CTA button mock ─────────────────────────────────────────────────────────
function CtaButton({ children, tone = 'green', size = 1 }) {
  const bg = tone === 'green' ? C.green : C.gold;
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 12, padding: `${16 * size}px ${34 * size}px`, borderRadius: 14, background: bg, color: tone === 'green' ? C.cream : C.ink, fontFamily: BODY, fontWeight: 700, fontSize: 24 * size, whiteSpace: 'nowrap', boxShadow: '0 10px 26px rgba(15,92,63,0.28)' }}>{children}</span>
  );
}

Object.assign(window, {
  C, FR, BODY, MONO, fadeOf, easeIO, easeOut,
  Vignette, PhotoScene, ColorField, MotifBand,
  CaptionBar, Kicker, Headline, StatCounter,
  LogoMark, Wordmark, LogoLockup, MatchRing,
  AppFrame, CheckRow, Chip, LangToggle, CtaButton,
});
