// ═══════════════════════════════════════════════════════════════════════
// Decorative SVGs & motion components — techy, motion-studio vocabulary
// ═══════════════════════════════════════════════════════════════════════

// ─── Brand glyph — bracketed monogram ───────────────────────────────────
function BrandGlyph({ letter = "A", size = 28 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 28 28" style={{ display: "block" }}>
      <g fill="none" stroke="var(--accent)" strokeWidth="1.5" strokeLinecap="square">
        <path d="M 3 5 L 3 3 L 7 3" />
        <path d="M 25 3 L 25 5" transform="translate(-4 0)" />
        <path d="M 21 3 L 25 3" />
        <path d="M 3 23 L 3 25 L 7 25" />
        <path d="M 21 25 L 25 25 L 25 23" />
      </g>
      <text
        x="14" y="20"
        textAnchor="middle"
        fontFamily="Space Grotesk, sans-serif"
        fontSize="16"
        fontWeight="600"
        fill="var(--ink)"
        letterSpacing="-0.04em"
      >{letter}</text>
    </svg>
  );
}

// ─── Skill meter — segmented LED bar ────────────────────────────────────
function SkillMeter({ level = 0.8, segments = 12 }) {
  const filled = Math.round(level * segments);
  const pct = Math.round(level * 100);
  return (
    <div className="skill-meter">
      {Array.from({ length: segments }).map((_, i) => (
        <span key={i} className={i < filled ? "seg on" : "seg"} />
      ))}
      <span className="pct">{pct}</span>
    </div>
  );
}

// ─── Live clock — UTC + studio location ─────────────────────────────────
function LiveClock({ tz = "Africa/Cairo" }) {
  const [t, setT] = React.useState(new Date());
  React.useEffect(() => {
    const id = setInterval(() => setT(new Date()), 1000);
    return () => clearInterval(id);
  }, []);
  let parts = { hour: "--", minute: "--", second: "--" };
  try {
    const fmt = new Intl.DateTimeFormat("en-GB", {
      timeZone: tz, hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false,
    });
    const formatted = fmt.format(t); // "HH:MM:SS"
    const [h, m, s] = formatted.split(":");
    parts = { hour: h, minute: m, second: s };
  } catch (e) { /* invalid timezone — keep placeholder */ }
  return (
    <span>
      {parts.hour}:{parts.minute}<span style={{ opacity: 0.5 }}>:{parts.second}</span>
    </span>
  );
}

// ─── Marquee — endlessly looping ticker ─────────────────────────────────
// Items duplicated once so the keyframe -50% translates seamlessly.
function Marquee({ items }) {
  return (
    <div className="marquee">
      <div className="marquee-track">
        {[...items, ...items].map((it, i) => (
          <span key={i} className="marquee-item">
            {it}
            <span className="sep">●</span>
          </span>
        ))}
      </div>
    </div>
  );
}

// ─── Frame counter — animated 0001 → 9999 style ─────────────────────────
function FrameCounter({ value = 1234, pad = 4, label = "Frame" }) {
  const [n, setN] = React.useState(0);
  React.useEffect(() => {
    let raf, start = 0;
    const dur = 1200;
    const step = (t) => {
      if (!start) start = t;
      const p = Math.min(1, (t - start) / dur);
      // ease-out
      const eased = 1 - Math.pow(1 - p, 3);
      setN(Math.round(eased * value));
      if (p < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [value]);
  return (
    <>
      <span style={{ color: "var(--mute)" }}>{label}</span>
      <b style={{ marginLeft: 6, fontVariantNumeric: "tabular-nums" }}>
        {String(n).padStart(pad, "0")}
      </b>
    </>
  );
}

// ─── Grid background — for hero or section accent ───────────────────────
function GridField({ rows = 12, cols = 18, opacity = 0.4 }) {
  return (
    <svg viewBox={`0 0 ${cols * 40} ${rows * 40}`}
         preserveAspectRatio="none"
         style={{ position: "absolute", inset: 0, width: "100%", height: "100%", opacity, pointerEvents: "none" }}>
      <g stroke="var(--line)" strokeWidth="1">
        {Array.from({ length: rows + 1 }).map((_, i) => (
          <line key={`h${i}`} x1="0" y1={i * 40} x2={cols * 40} y2={i * 40} />
        ))}
        {Array.from({ length: cols + 1 }).map((_, i) => (
          <line key={`v${i}`} x1={i * 40} y1="0" x2={i * 40} y2={rows * 40} />
        ))}
      </g>
      <g fill="var(--accent)">
        {[ [2, 3], [7, 1], [12, 4], [15, 2], [4, 8], [10, 6], [16, 9] ].map(([c, r], i) => (
          <circle key={i} cx={c * 40} cy={r * 40} r="2.5" opacity={0.7 - i * 0.05} />
        ))}
      </g>
    </svg>
  );
}

// ─── Scramble text — settles random chars into final string ─────────────
function Scramble({ text, dur = 800, className }) {
  const [out, setOut] = React.useState(text);
  React.useEffect(() => {
    const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@#$%&*";
    let frame = 0;
    const total = Math.ceil(dur / 32);
    let raf;
    const tick = () => {
      frame++;
      const p = frame / total;
      const settled = Math.floor(p * text.length);
      let s = "";
      for (let i = 0; i < text.length; i++) {
        if (i < settled || text[i] === " ") s += text[i];
        else s += chars[Math.floor(Math.random() * chars.length)];
      }
      setOut(s);
      if (frame < total) raf = requestAnimationFrame(tick);
      else setOut(text);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [text, dur]);
  return <span className={className}>{out}</span>;
}

// ─── Timecode chip — fake video timecode ────────────────────────────────
function Timecode({ time = "01:24:08:12" }) {
  return <span className="timecode">{time}</span>;
}

// ─── Status LED — tagged status pill ────────────────────────────────────
function StatusTag({ children, color = "accent" }) {
  return (
    <span className={`tag ${color}`}>
      <span className="led" />
      {children}
    </span>
  );
}

// ─── Discipline chip ─────────────────────────────────────────────────────
function DisciplineTag({ children }) {
  return <span className="tag">{children}</span>;
}

window.BrandGlyph = BrandGlyph;
window.SkillMeter = SkillMeter;
window.LiveClock = LiveClock;
window.Marquee = Marquee;
window.FrameCounter = FrameCounter;
window.GridField = GridField;
window.Scramble = Scramble;
window.Timecode = Timecode;
window.StatusTag = StatusTag;
window.DisciplineTag = DisciplineTag;
