// components.jsx — shared building blocks for the DSCR video

// ── Brand tokens — matched to National Mortgage Center brand guide ──────────
// Old Glory Blue #0A3161  (primary)
// Old Glory Red  #B31942  (accent)
// Basic White    #FFFFFF
const BRAND = {
  navy:      '#0A3161',  // Old Glory Blue — primary
  navyDeep:  '#05122A',  // richer background variant
  navyMid:   '#0F3E7A',  // hover / secondary
  cream:     '#FFFFFF',  // Basic White
  creamDim:  '#E6EBF3',  // pale blue-tinted white
  ink:       '#050F1E',
  red:       '#B31942',  // Old Glory Red — reserved for semantic warning/shortfall states
  redDim:    '#8A1234',  // darker red
  redBright: '#D42150',  // brighter accent for glows
  accent:    '#90C8FF',  // light cornflower blue — decorative accent (matches NMC site "POPULAR PATHS" chip)
  accentDim: '#6BA8E8',  // darker light blue for gradients
  accentSoft:'rgba(144, 200, 255, 0.15)',  // for pill backgrounds
  green:     '#3DDC97',  // bright mint — reads as positive/growth against navy
  greenDim:  '#2AB679',  // slightly deeper mint for gradients
  slate:     '#8B9BB4',
  slateDim:  '#4A5D7A',
  hairline:  'rgba(255, 255, 255, 0.14)',
  hairlineDark: 'rgba(10, 49, 97, 0.20)',
};

const FONT_DISPLAY = "'Montserrat', system-ui, sans-serif";       // for headings — matches logo wordmark
const FONT_SERIF   = "'Playfair Display', Georgia, serif";        // editorial accents (italic emphasis)
const FONT_UI      = "'Montserrat', system-ui, sans-serif";       // body / UI (same family, lighter weights)
const FONT_MONO    = "'Geist Mono', 'JetBrains Mono', ui-monospace, monospace";

// ── Film grain + vignette overlay ───────────────────────────────────────────
function FilmOverlay({ intensity = 0.35 }) {
  const time = useTime();
  // subtle animated grain via SVG turbulence
  return (
    <>
      {/* Vignette */}
      <div style={{
        position: 'absolute', inset: 0,
        pointerEvents: 'none',
        background: 'radial-gradient(ellipse at center, transparent 40%, rgba(0,0,0,0.55) 100%)',
        zIndex: 90,
      }}/>
      {/* Grain */}
      <div style={{
        position: 'absolute', inset: 0,
        pointerEvents: 'none',
        opacity: intensity,
        mixBlendMode: 'overlay',
        zIndex: 91,
        backgroundImage: `url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='300' height='300'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='2' stitchTiles='stitch'/><feColorMatrix values='0 0 0 0 0.9  0 0 0 0 0.85  0 0 0 0 0.7  0 0 0 0.5 0'/></filter><rect width='300' height='300' filter='url(%23n)' opacity='0.85'/></svg>")`,
        backgroundSize: '300px 300px',
        transform: `translate(${Math.sin(time * 30) * 2}px, ${Math.cos(time * 27) * 2}px)`,
      }}/>
    </>
  );
}

// ── Letterbox bars for cinematic moments ────────────────────────────────────
function Letterbox({ show = true, height = 100 }) {
  return (
    <>
      <div style={{
        position: 'absolute', left: 0, right: 0, top: 0,
        height, background: '#000',
        transform: `translateY(${show ? 0 : -height}px)`,
        transition: 'transform 500ms cubic-bezier(0.65, 0, 0.35, 1)',
        zIndex: 80,
      }}/>
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0,
        height, background: '#000',
        transform: `translateY(${show ? 0 : height}px)`,
        transition: 'transform 500ms cubic-bezier(0.65, 0, 0.35, 1)',
        zIndex: 80,
      }}/>
    </>
  );
}

// ── Number counter — counts from -> to over duration ────────────────────────
function NumberCount({ from, to, start = 0, end = 1, prefix = '', suffix = '', decimals = 0, ease = Easing.easeOutCubic }) {
  const t = useTime();
  const p = clamp((t - start) / (end - start), 0, 1);
  const v = from + (to - from) * ease(p);
  const s = v.toFixed(decimals);
  // add thousands separator
  const [ip, dp] = s.split('.');
  const ipf = ip.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  return <>{prefix}{ipf}{dp ? '.' + dp : ''}{suffix}</>;
}

// ── Kaption / lower third ───────────────────────────────────────────────────
function Caption({ children, y = 940 }) {
  const { progress, duration } = useSprite();
  const opacity = progress < 0.08 ? progress / 0.08 : progress > 0.92 ? (1 - progress) / 0.08 : 1;
  return (
    <div style={{
      position: 'absolute',
      left: '50%', top: y,
      transform: 'translateX(-50%)',
      opacity,
      color: BRAND.creamDim,
      fontFamily: FONT_MONO,
      fontSize: 18,
      letterSpacing: '0.24em',
      textTransform: 'uppercase',
      textAlign: 'center',
      zIndex: 40,
    }}>
      <span style={{
        display: 'inline-block',
        width: 40, height: 1, background: BRAND.accent,
        verticalAlign: 'middle', marginRight: 20,
      }}/>
      {children}
      <span style={{
        display: 'inline-block',
        width: 40, height: 1, background: BRAND.accent,
        verticalAlign: 'middle', marginLeft: 20,
      }}/>
    </div>
  );
}

// ── Chip / pill ─────────────────────────────────────────────────────────────
function Chip({ label, delay = 0, x, y, width, accent = false }) {
  const t = useTime();
  const p = clamp((t - delay) / 0.5, 0, 1);
  const e = Easing.easeOutBack(p);
  return (
    <div style={{
      position: 'absolute',
      left: x, top: y,
      width,
      padding: '18px 30px',
      background: accent ? BRAND.accent : 'rgba(245, 241, 234, 0.04)',
      border: `1px solid ${accent ? BRAND.accent : BRAND.hairline}`,
      borderRadius: 999,
      color: accent ? BRAND.navy : BRAND.cream,
      fontFamily: FONT_UI,
      fontSize: 26,
      fontWeight: 500,
      letterSpacing: '-0.01em',
      textAlign: 'center',
      opacity: p,
      transform: `translateY(${(1 - e) * 30}px) scale(${0.9 + 0.1 * e})`,
      backdropFilter: 'blur(20px)',
      whiteSpace: 'nowrap',
    }}>
      {label}
    </div>
  );
}

// ── Section frame — background + optional label ─────────────────────────────
function SceneBg({ color = BRAND.navy, children, gradient = false }) {
  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: gradient
        ? `radial-gradient(ellipse at 50% 40%, ${BRAND.navy} 0%, ${BRAND.navyDeep} 100%)`
        : color,
      overflow: 'hidden',
    }}>
      {children}
    </div>
  );
}

// ── Slow pan/zoom wrapper (Ken Burns) ────────────────────────────────────────
function KenBurns({ children, from = 1, to = 1.08, tx = 0, ty = 0 }) {
  const { progress } = useSprite();
  const scale = from + (to - from) * progress;
  return (
    <div style={{
      position: 'absolute', inset: 0,
      transform: `scale(${scale}) translate(${tx * progress}px, ${ty * progress}px)`,
      transformOrigin: 'center',
      willChange: 'transform',
    }}>
      {children}
    </div>
  );
}

// ── Highlight bar (animated underline) ──────────────────────────────────────
function HighlightBar({ x, y, width, height = 4, color = BRAND.accent, delay = 0, dur = 0.6 }) {
  const t = useTime();
  const p = clamp((t - delay) / dur, 0, 1);
  const e = Easing.easeInOutQuart(p);
  return (
    <div style={{
      position: 'absolute',
      left: x, top: y,
      width: width * e, height,
      background: color,
      transformOrigin: 'left',
    }}/>
  );
}

// ── DSCR gauge — horizontal bar with needle sweep ───────────────────────────
function DSCRGauge({ x, y, width = 1200, needleValue = 1.21, startTime = 0, sweepDur = 2 }) {
  const t = useTime();
  const sweepP = clamp((t - startTime) / sweepDur, 0, 1);
  const eased = Easing.easeInOutCubic(sweepP);

  // Value range shown: 0.6 → 1.6
  const MIN = 0.6, MAX = 1.6;
  const currentVal = MIN + (needleValue - MIN) * eased;

  const valToPct = (v) => ((v - MIN) / (MAX - MIN)) * 100;

  const marks = [
    { v: 0.80, label: '0.80' },
    { v: 1.00, label: '1.00', big: true, sub: 'break-even' },
    { v: 1.21, label: '1.21', gold: true },
    { v: 1.40, label: '1.40' },
  ];

  return (
    <div style={{
      position: 'absolute',
      left: x, top: y,
      width,
    }}>
      {/* Track */}
      <div style={{
        position: 'relative',
        height: 12,
        background: 'linear-gradient(to right, #B31942 0%, #B31942 40%, #FFFFFF 40%, #FFFFFF 42%, #3DDC97 42%, #3DDC97 100%)',
        borderRadius: 999,
        boxShadow: 'inset 0 2px 6px rgba(0,0,0,0.3)',
      }}>
        {/* 1.00 divider */}
        <div style={{
          position: 'absolute',
          left: `${valToPct(1.0)}%`,
          top: -6, bottom: -6,
          width: 2, background: BRAND.cream,
          transform: 'translateX(-1px)',
        }}/>

        {/* Needle */}
        <div style={{
          position: 'absolute',
          left: `${valToPct(currentVal)}%`,
          top: -30, bottom: -30,
          width: 4,
          marginLeft: -2,
          background: BRAND.cream,
          boxShadow: '0 0 20px rgba(245,241,234,0.6)',
          borderRadius: 2,
        }}>
          <div style={{
            position: 'absolute',
            left: '50%', top: -44,
            transform: 'translateX(-50%)',
            background: BRAND.cream,
            color: BRAND.navy,
            padding: '6px 14px',
            borderRadius: 6,
            fontFamily: FONT_MONO,
            fontSize: 22,
            fontWeight: 600,
            letterSpacing: '-0.01em',
            whiteSpace: 'nowrap',
          }}>
            {currentVal.toFixed(2)}
          </div>
        </div>
      </div>

      {/* Marks */}
      <div style={{ position: 'relative', height: 60, marginTop: 12 }}>
        {marks.map(m => (
          <div key={m.v} style={{
            position: 'absolute',
            left: `${valToPct(m.v)}%`,
            transform: 'translateX(-50%)',
            textAlign: 'center',
            color: m.gold ? BRAND.accent : BRAND.creamDim,
            fontFamily: FONT_MONO,
            fontSize: m.big ? 18 : 15,
            fontWeight: 500,
          }}>
            <div>{m.label}</div>
            {m.sub && <div style={{
              fontSize: 12, letterSpacing: '0.16em',
              textTransform: 'uppercase', marginTop: 4,
              color: BRAND.slate,
            }}>{m.sub}</div>}
          </div>
        ))}
      </div>

      {/* Range labels */}
      <div style={{
        display: 'flex', justifyContent: 'space-between',
        marginTop: 24,
        fontFamily: FONT_UI, fontSize: 20, fontWeight: 400,
      }}>
        <div style={{ color: BRAND.accent, letterSpacing: '-0.01em' }}>
          <span style={{ fontFamily: FONT_MONO, fontSize: 16, opacity: 0.7 }}>◀ </span>
          Income shortfall
        </div>
        <div style={{ color: BRAND.green, letterSpacing: '-0.01em' }}>
          Income exceeds debt
          <span style={{ fontFamily: FONT_MONO, fontSize: 16, opacity: 0.7 }}> ▶</span>
        </div>
      </div>
    </div>
  );
}

// ── Property card mockup — visual for use-cases scene ───────────────────────
function PropertyCard({ x, y, width = 280, height = 200, label, price, rent, tag, delay = 0 }) {
  const t = useTime();
  const p = clamp((t - delay) / 0.6, 0, 1);
  const e = Easing.easeOutCubic(p);
  return (
    <div style={{
      position: 'absolute',
      left: x, top: y,
      width, height,
      borderRadius: 12,
      overflow: 'hidden',
      background: 'linear-gradient(135deg, #1E3457 0%, #0B1F3A 100%)',
      border: `1px solid ${BRAND.hairline}`,
      opacity: p,
      transform: `translateY(${(1 - e) * 20}px) scale(${0.95 + 0.05 * e})`,
      boxShadow: '0 30px 60px rgba(0,0,0,0.4)',
    }}>
      {/* Illustrated "roof" */}
      <div style={{
        position: 'relative',
        height: '55%',
        background: 'linear-gradient(180deg, rgba(212,162,76,0.15) 0%, rgba(11,31,58,0) 100%)',
        borderBottom: `1px solid ${BRAND.hairline}`,
      }}>
        <svg width="100%" height="100%" viewBox="0 0 280 110" preserveAspectRatio="none">
          {/* Roof */}
          <path d="M 30 90 L 140 30 L 250 90 Z" fill="none" stroke={BRAND.accent} strokeWidth="2" opacity="0.6"/>
          {/* House body */}
          <rect x="55" y="60" width="170" height="45" fill="none" stroke={BRAND.creamDim} strokeWidth="1.5" opacity="0.5"/>
          {/* Door */}
          <rect x="130" y="80" width="20" height="25" fill="none" stroke={BRAND.creamDim} strokeWidth="1" opacity="0.5"/>
          {/* Windows */}
          <rect x="75" y="75" width="18" height="15" fill="none" stroke={BRAND.creamDim} strokeWidth="1" opacity="0.4"/>
          <rect x="187" y="75" width="18" height="15" fill="none" stroke={BRAND.creamDim} strokeWidth="1" opacity="0.4"/>
        </svg>
        {tag && (
          <div style={{
            position: 'absolute', top: 12, right: 12,
            padding: '4px 10px',
            background: BRAND.accent,
            color: BRAND.navy,
            fontFamily: FONT_MONO,
            fontSize: 10,
            letterSpacing: '0.14em',
            textTransform: 'uppercase',
            borderRadius: 4,
            fontWeight: 600,
          }}>
            {tag}
          </div>
        )}
      </div>
      {/* Details */}
      <div style={{ padding: '14px 18px', color: BRAND.cream }}>
        <div style={{
          fontFamily: FONT_UI, fontSize: 12, fontWeight: 500,
          letterSpacing: '0.12em', textTransform: 'uppercase',
          color: BRAND.slate, marginBottom: 6,
        }}>{label}</div>
        <div style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
        }}>
          <div style={{ fontFamily: FONT_UI, fontSize: 22, fontWeight: 600 }}>{price}</div>
          <div style={{ fontFamily: FONT_MONO, fontSize: 13, color: BRAND.creamDim }}>{rent}/mo</div>
        </div>
      </div>
    </div>
  );
}

// ── Scene divider marker (fade transition between scenes) ───────────────────
function SceneFade({ start, end, color = '#000', fadeIn = 0.25, fadeOut = 0.25 }) {
  const t = useTime();
  if (t < start || t > end) return null;
  const localT = t - start;
  const dur = end - start;
  let alpha = 1;
  if (localT < fadeIn) alpha = localT / fadeIn;
  else if (localT > dur - fadeOut) alpha = (dur - localT) / fadeOut;
  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: color, opacity: alpha,
      pointerEvents: 'none', zIndex: 99,
    }}/>
  );
}

Object.assign(window, {
  BRAND, FONT_DISPLAY, FONT_SERIF, FONT_UI, FONT_MONO,
  FilmOverlay, Letterbox, NumberCount, Caption, Chip,
  SceneBg, KenBurns, HighlightBar, DSCRGauge, PropertyCard, SceneFade,
});
