// video-elements.jsx — VikingHeat infografik: house, triangle, and corner pods

// ── House (comfort core) ───────────────────────────────────────────────────
// Lifecycle:
//   t < 3       : not rendered
//   3 → 5       : draws in (stroke-dash) at center stage, large (320×320)
//   5 → 7       : 100% core fades in & pulses
//   7 → 8.2     : house shrinks + slides to triangle centroid (small ~140×140)
//   8.2 → end   : remains at centroid, gentle pulse
// During scene 4 (11–15s), inner sensors light up; otherwise quiet.

function CenterHouse() {
  const t = useTime();
  if (t < 2.6 || t > 23.2) return null;

  // Phase A: large at centre stage (centred horizontally, ~y 600).
  const bigCx = W / 2, bigCy = 600, bigSize = 380;
  // Phase B: prominent at triangle centroid (the comfort core).
  const smCx = TRI.cx, smCy = TRI.cy, smSize = 320;

  // Migration progress: 0 = at centre stage big; 1 = small at centroid
  const mig = smooth(ramp(t, 7.0, 8.4));

  // Fade out before Twins scene
  const houseOp = fadeWindow(t, 2.6, 2.7, 22.6, 23.2);
  const cx = lerp(bigCx, smCx, mig);
  const cy = lerp(bigCy, smCy, mig);
  const size = lerp(bigSize, smSize, mig);

  // Draw-in: stroke dash from t=2.8..4.4
  const drawT = smooth(ramp(t, 2.8, 4.4));

  // Comfort core fade-in 4.6..5.6
  const coreFade = smooth(ramp(t, 4.6, 5.6));
  // Pulse breathing
  const pulse = 1 + 0.04 * Math.sin((t - 4.6) * Math.PI * 1.2);

  // Sensor activity (scene A — 11..15)
  const sensorOn = fadeWindow(t, 10.8, 11.6, 14.6, 15.2);

  // Sensors emit data toward A corner (11..14.6)
  const flowOn = fadeWindow(t, 11.6, 12.4, 14.4, 15.0);

  const half = size / 2;
  const x = cx - half, y = cy - half;
  // House silhouette: roof apex top-mid, base box. Drawn in svg local coords 0..100.
  const path = "M 10 50 L 50 14 L 90 50 L 90 92 L 10 92 Z";
  const wallPath = "M 90 50 L 90 92 L 10 92 L 10 50";
  const roofPath = "M 10 50 L 50 14 L 90 50";

  // Sensor positions in 0..100 local
  const sensors = [
    { x: 28, y: 78, name: 'gulv'   },
    { x: 72, y: 78, name: 'gulv'   },
    { x: 30, y: 60, name: 'rum'    },
    { x: 70, y: 60, name: 'rum'    },
    { x: 50, y: 70, name: 'rum'    },
    { x: 22, y: 86, name: 'væg'    },
    { x: 78, y: 86, name: 'væg'    },
  ];

  return (
    <div style={{
      position: 'absolute', left: x, top: y, width: size, height: size,
      pointerEvents: 'none', opacity: houseOp,
    }}>
      <svg viewBox="0 0 100 100" width={size} height={size} style={{ overflow: 'visible' }}>
        {/* glow ring around house when comfort core is active */}
        <circle cx="50" cy="60" r="56"
          fill="none" stroke={VC.copper}
          strokeWidth="0.4" opacity={0.18 * coreFade * pulse} />
        <circle cx="50" cy="60" r="48"
          fill="none" stroke={VC.copper}
          strokeWidth="0.3" opacity={0.10 * coreFade} />

        {/* roof — drawn first */}
        <path d={roofPath} fill="none" stroke={VC.houseStroke || VC.paper} strokeWidth="1.4"
          strokeLinecap="round" strokeLinejoin="round"
          pathLength={1} strokeDasharray={1} strokeDashoffset={1 - drawT * 0.45} />
        {/* walls — drawn after */}
        <path d={wallPath} fill="none" stroke={VC.houseStroke || VC.paper} strokeWidth="1.4"
          strokeLinecap="round" strokeLinejoin="round"
          pathLength={1} strokeDasharray={1}
          strokeDashoffset={1 - Math.max(0, drawT - 0.35) * (1/0.65)} />
        {/* fill subtle */}
        <path d={path} fill={VC.ink2} opacity={0.5 * drawT} />

        {/* horizontal floor lines (ground level interior cue) */}
        <line x1="14" y1="78" x2="86" y2="78"
          stroke={VC.line} strokeWidth="0.3" opacity={0.6 * drawT} />

        {/* Comfort core ── soft green halo behind 100% text. Larger, lower opacity */}
        <g opacity={coreFade}>
          <circle cx="50" cy="60" r={36 * pulse} fill={VC.copper} opacity={0.05} />
          <circle cx="50" cy="60" r={28 * pulse} fill={VC.copper} opacity={0.08} />
          <circle cx="50" cy="60" r="22" fill={VC.copper} opacity={0.13} />
          <circle cx="50" cy="60" r="17" fill={VC.copper} opacity={0.18}/>
        </g>

        {/* Sensors (scene A) */}
        {sensors.map((s, i) => {
          const phase = (t * 1.6 + i * 0.5) % 1;
          const r = 1.2 + phase * 1.6;
          const op = sensorOn * (0.35 + 0.65 * (1 - phase));
          return (
            <g key={i} opacity={op}>
              <circle cx={s.x} cy={s.y} r={r} fill="none"
                stroke={VC.copper} strokeWidth="0.25" />
              <circle cx={s.x} cy={s.y} r="0.9" fill={VC.copper} />
            </g>
          );
        })}

        {/* Data flow lines from sensors up to A corner — only during scene A */}
        {flowOn > 0.05 && sensors.slice(0, 5).map((s, i) => {
          // Local svg → stage line: A is up & out of svg. We just draw a short
          // upward streak inside svg; full beam to A is drawn at stage level.
          const flowT = ((t * 0.8 + i * 0.13) % 1);
          return (
            <line key={`f${i}`}
              x1={s.x} y1={s.y - 1}
              x2={s.x} y2={s.y - 1 - 8 * flowT}
              stroke={VC.copper} strokeWidth="0.3"
              opacity={flowOn * (1 - flowT) * 0.7} />
          );
        })}
      </svg>

      {/* HTML text overlay for "100%" on top of puck — crisp at any scale */}
      <div style={{
        position: 'absolute',
        left: '50%', top: '60%',
        transform: 'translate(-50%, -50%)',
        display: 'flex', flexDirection: 'column', alignItems: 'center',
        gap: Math.round(size * 0.018),
        opacity: coreFade, pointerEvents: 'none',
        textShadow: `0 1px 6px rgba(0,0,0,0.35)`,
      }}>
        <div style={{
          fontFamily: VC.fontSans, fontWeight: 600,
          fontSize: Math.round(size * 0.115), color: VC.houseStroke || VC.paper,
          letterSpacing: '-0.02em', lineHeight: 1,
        }}>100%</div>
        <div style={{
          fontFamily: VC.fontMono, fontWeight: 500,
          fontSize: Math.round(size * 0.04), color: VC.houseStroke || VC.paper,
          letterSpacing: '0.18em', lineHeight: 1,
          textTransform: 'uppercase', opacity: 0.9,
        }}>Komfort</div>
      </div>

      {/* Comfort caption — always visible while house is on stage */}
      {t > 4.6 && (
        <div style={{
          position: 'absolute', left: '50%', bottom: -56,
          transform: 'translateX(-50%)',
          fontFamily: VC.fontMono, fontSize: 14,
          letterSpacing: '0.18em', color: VC.copper,
          opacity: fadeWindow(t, 4.9, 5.6, 22.4, 23.0),
          textTransform: 'uppercase', whiteSpace: 'nowrap',
        }}>
          KOMFORT · ØNSKET TEMPERATUR ALTID BEVARET
        </div>
      )}
    </div>
  );
}

// ── Triangle ───────────────────────────────────────────────────────────────
// Visible 7..27 — draws in 7..9, holds, then fades 26..27.
// `focus` arg ('A'|'B'|'C'|null) emphasises one corner.
function TriangleField() {
  const t = useTime();
  if (t < 6.8 || t > 23.4) return null;

  // 0..1 path-draw progress (3 sides drawn sequentially)
  const drawT = smooth(ramp(t, 7.0, 9.0));

  const focus = (() => {
    if (t >= 11 && t < 15)  return 'A';
    if (t >= 15 && t < 19)  return 'B';
    if (t >= 19 && t < 23)  return 'C';
    return null;
  })();

  // Overall opacity (fades out before Twins scene takes over the centre)
  const op = fadeWindow(t, 6.8, 7.2, 22.6, 23.2);

  // Corner activation: for each corner, 0..1 lit value.
  const cornerLit = (key) => {
    // base lit-in at start of triangle reveal: 0..1 over 8.0..9.5 staggered
    const idx = key === 'A' ? 0 : key === 'B' ? 1 : 2;
    const baseFade = smooth(ramp(t, 8.0 + idx * 0.4, 9.0 + idx * 0.4));
    const focused = focus === key ? 1 : (focus ? 0.35 : 0.7);
    return baseFade * focused;
  };

  // Edge stroke: draw 3 sides in sequence
  const seg = (a, b, segStart, segEnd) => {
    const sp = smooth(ramp(t, segStart, segEnd));
    const x2 = lerp(a.x, b.x, sp);
    const y2 = lerp(a.y, b.y, sp);
    const focusEdge = focus && (focus === a.key || focus === b.key);
    return (
      <line x1={a.x} y1={a.y} x2={x2} y2={y2}
        stroke={focusEdge ? VC.paper : VC.line}
        strokeWidth={focusEdge ? 2 : 1.4}
        strokeOpacity={focusEdge ? 0.85 : 0.7}
        strokeLinecap="round" />
    );
  };

  return (
    <svg width={W} height={H}
      style={{ position: 'absolute', inset: 0, opacity: op, pointerEvents: 'none' }}>
      {/* faint inner triangle fill once drawn */}
      <polygon
        points={`${TRI.A.x},${TRI.A.y} ${TRI.B.x},${TRI.B.y} ${TRI.C.x},${TRI.C.y}`}
        fill={VC.ink3} opacity={0.20 * drawT} />

      {/* edges — drawn in sequence A→B, B→C, C→A */}
      {seg(TRI.A, TRI.B, 7.1, 7.7)}
      {seg(TRI.B, TRI.C, 7.7, 8.3)}
      {seg(TRI.C, TRI.A, 8.3, 8.9)}

      {/* corner pods */}
      {['A','B','C'].map(key => {
        const c = TRI[key];
        const lit = cornerLit(key);
        const r = 28 + 6 * Math.sin((t + key.charCodeAt(0)) * 1.5);
        return (
          <g key={key} opacity={smooth(ramp(t, 8.0, 9.2))}>
            {/* halo */}
            <circle cx={c.x} cy={c.y} r={r} fill={c.color} opacity={0.10 * (0.4 + lit)} />
            <circle cx={c.x} cy={c.y} r={r * 0.6} fill={c.color} opacity={0.18 * (0.4 + lit)} />
            {/* dot */}
            <circle cx={c.x} cy={c.y} r="11" fill={c.color}
              stroke={VC.paper} strokeOpacity={lit * 0.5} strokeWidth="2" />
            <circle cx={c.x} cy={c.y} r="4" fill={VC.ink} opacity={0.7} />
          </g>
        );
      })}

      {/* labels next to each corner */}
      {['A','B','C'].map(key => {
        const c = TRI[key];
        const labelOp = smooth(ramp(t, 8.6 + (key==='A'?0:key==='B'?0.3:0.6), 9.6 + (key==='A'?0:key==='B'?0.3:0.6)));
        // place labels offset outward
        let lx = c.x, ly = c.y, anchor = 'middle';
        if (key === 'A') { ly = c.y - 92; }
        if (key === 'B') { lx = c.x + 36; ly = c.y + 6; anchor = 'start'; }
        if (key === 'C') { lx = c.x - 36; ly = c.y + 6; anchor = 'end'; }
        return (
          <text key={`lbl-${key}`} x={lx} y={ly}
            textAnchor={anchor} dominantBaseline="middle"
            fontFamily={VC.fontMono} fontSize="20" letterSpacing="2"
            fill={c.color} opacity={labelOp}
            fontWeight="500">
            {c.label}
          </text>
        );
      })}
    </svg>
  );
}

// Beams of data flowing from a corner toward the centroid (during that corner's scene)
function CornerBeams() {
  const t = useTime();
  // Active during 11..23 only (each corner's scene)
  if (t < 10.8 || t > 23.4) return null;

  const segs = [
    { from: TRI.A, sceneStart: 11, sceneEnd: 15 }, // A
    { from: TRI.B, sceneStart: 15, sceneEnd: 19 }, // B
    { from: TRI.C, sceneStart: 19, sceneEnd: 23 }, // C
  ];

  return (
    <svg width={W} height={H}
      style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}>
      {segs.map((s, i) => {
        if (t < s.sceneStart - 0.4 || t > s.sceneEnd + 0.4) return null;
        const op = fadeWindow(t, s.sceneStart - 0.2, s.sceneStart + 0.5, s.sceneEnd - 0.5, s.sceneEnd + 0.2);
        const dx = TRI.cx - s.from.x;
        const dy = TRI.cy - s.from.y;
        // Animate 3 dots along the beam from corner→center
        const dots = [0, 0.33, 0.66].map((offset, j) => {
          const phase = ((t * 0.7) + offset) % 1;
          const px = s.from.x + dx * phase;
          const py = s.from.y + dy * phase;
          return (
            <circle key={j} cx={px} cy={py} r="5"
              fill={s.from.color} opacity={op * (1 - phase) * 0.9} />
          );
        });
        return (
          <g key={i}>
            <line x1={s.from.x} y1={s.from.y} x2={TRI.cx} y2={TRI.cy}
              stroke={s.from.color} strokeWidth="1.2"
              strokeDasharray="4 6" strokeOpacity={0.45 * op} />
            {dots}
          </g>
        );
      })}
    </svg>
  );
}

Object.assign(window, { CenterHouse, TriangleField, CornerBeams });
