// Generative calendar block — Hero right-side animation
//
// 7 day columns (Mon–Sun). Each day has ~5–7 task "cards" (filled rectangles
// of varying height, color-coded by AI employee). Cards appear progressively
// over ~8s, filling the week. A small live counter ticks up at the bottom.
//
//   Watchdog — ink (dark)    — sparse, anchored (audits, SOPs)
//   Ezra     — oxblood       — the bulk (knowledge work, ops)
//   Mia      — sage/secondary — clusters (calls, scheduling)
//
// Loops every ~12s with a different seed so the layout varies slightly.

const { useState: useCalState, useEffect: useCalEffect, useMemo: useCalMemo, useRef: useCalRef } = React;

const DAYS = ["M", "T", "W", "T", "F", "S", "S"];
const OWNERS = ["watchdog", "ezra", "mia"];

// Seeded PRNG for stable layouts per run
function mulberry(seed) {
  let t = seed;
  return () => {
    t |= 0; t = (t + 0x6D2B79F5) | 0;
    let r = Math.imul(t ^ (t >>> 15), 1 | t);
    r = (r + Math.imul(r ^ (r >>> 7), 61 | r)) ^ r;
    return ((r ^ (r >>> 14)) >>> 0) / 4294967296;
  };
}

// Generate one week's worth of cards
// Each card: { dayIdx, owner, top (0-1), height (0-1), delay (ms) }
function generateWeek(seed) {
  const rng = mulberry(seed);
  const cards = [];
  let totalDelay = 0;

  // For each day, lay down a stack of cards top-to-bottom
  for (let d = 0; d < 7; d++) {
    let y = 0.02 + rng() * 0.05; // top padding
    const cardCount = 4 + Math.floor(rng() * 4); // 4-7 cards per day

    for (let c = 0; c < cardCount && y < 0.92; c++) {
      // Pick owner with weighted distribution: ezra dominant
      const r = rng();
      let owner;
      if (r < 0.15) owner = "watchdog";
      else if (r < 0.70) owner = "ezra";
      else owner = "mia";

      // Height varies by owner
      let h;
      if (owner === "watchdog") h = 0.08 + rng() * 0.14; // taller, anchored
      else if (owner === "ezra") h = 0.04 + rng() * 0.10;  // medium
      else h = 0.03 + rng() * 0.06;                         // shorter bursts

      if (y + h > 0.96) break;

      // Slight inset / width variation so not all cards are full-width
      const inset = rng() < 0.3 ? 0.08 + rng() * 0.15 : 0;
      const rightInset = rng() < 0.25 ? 0.05 + rng() * 0.1 : 0;

      cards.push({
        dayIdx: d,
        owner,
        top: y,
        height: h,
        inset,
        rightInset,
        delay: totalDelay,
        id: `${seed}-${d}-${c}`,
      });

      y += h + 0.012 + rng() * 0.018; // gap
      totalDelay += 35 + Math.floor(rng() * 80);
    }
  }

  // Shuffle delays so cards don't appear strictly day-by-day
  // Let it feel more like the week is filling organically
  const shuffled = cards.slice().sort(() => rng() - 0.5);
  let t = 100;
  shuffled.forEach((card) => {
    card.delay = t;
    t += 60 + Math.floor(rng() * 90);
  });

  return cards;
}

function useLiveCount(target, durationMs) {
  const [n, setN] = useCalState(0);
  useCalEffect(() => {
    let cancelled = false;
    const start = performance.now();
    function tick() {
      if (cancelled) return;
      const t = Math.min(1, (performance.now() - start) / durationMs);
      // ease-out
      const e = 1 - Math.pow(1 - t, 2.5);
      setN(Math.floor(target * e));
      if (t < 1) requestAnimationFrame(tick);
    }
    requestAnimationFrame(tick);
    return () => { cancelled = true; };
  }, [target, durationMs]);
  return n;
}

function CalendarBlock() {
  const [runId, setRunId] = useCalState(0);
  const seed = 100 + runId * 37;

  const cards = useCalMemo(() => generateWeek(seed), [seed]);
  const maxDelay = useCalMemo(
    () => cards.reduce((m, c) => Math.max(m, c.delay), 0),
    [cards]
  );

  // Target count — bump by a few hundred each cycle so it feels cumulative
  const baseCount = 1284 + runId * 37;
  const liveCount = useLiveCount(baseCount, Math.max(2000, maxDelay + 600));

  // Loop: clear → regenerate
  useCalEffect(() => {
    const id = setTimeout(() => setRunId(r => r + 1), maxDelay + 5500);
    return () => clearTimeout(id);
  }, [maxDelay, runId]);

  return (
    <div className="calblock" aria-hidden="true">
      <div className="calblock-head">
        <div className="calblock-eyebrow">
          <span className="cdot" />
          <span>WEEK OF APR 22</span>
        </div>
        <div className="calblock-legend">
          <span><i className="dot-w" />Watchdog</span>
          <span><i className="dot-e" />Ezra</span>
          <span><i className="dot-m" />Mia</span>
        </div>
      </div>

      <div className="calblock-grid" key={runId}>
        {DAYS.map((d, i) => (
          <div className="calblock-col" key={i}>
            <div className="calblock-daylabel">{d}</div>
            <div className="calblock-daybody">
              {cards
                .filter(c => c.dayIdx === i)
                .map(card => (
                  <div
                    key={card.id}
                    className={`calcard ${card.owner}`}
                    style={{
                      top: `${card.top * 100}%`,
                      height: `${card.height * 100}%`,
                      left: `${card.inset * 100}%`,
                      right: `${card.rightInset * 100}%`,
                      animationDelay: `${card.delay}ms`,
                    }}
                  />
                ))}
            </div>
          </div>
        ))}
      </div>

      <div className="calblock-foot">
        <div className="calblock-count">
          <span className="calblock-num">{liveCount.toLocaleString()}</span>
          <span className="calblock-lbl">items handled this week</span>
        </div>
        <div className="calblock-caption">A week, on shift.</div>
      </div>
    </div>
  );
}

window.CalendarBlock = CalendarBlock;
