// Shared loading screen — the MagicRascals star doing its thing, over a
// faint sketch of the page that's about to appear. One component, used by
// Sheets, Rooms, the list page and anything else that waits on Supabase.
//
//   <MrLoading page="sheets" />                 full page
//   <MrLoading page="list" size="compact" />    inside an embedded panel
//
// `page` picks the background sketch and the rotating lines:
//   sheets · rooms · list · lists · library · (anything else → generic rows)

const MR_LOADING_LINES = {
  sheets:  ['Lining up the columns…', 'Counting what’s done…', 'Folding muslins…', 'Checking who loved what…'],
  rooms:   ['Measuring the walls…', 'Finding the door…', 'Nudging the cot flush…', 'Rolling the pram in…'],
  list:    ['Opening the list…', 'Fetching the pictures…', 'Counting socks…', 'Warming bottles…'],
  lists:   ['Gathering your lists…', 'Counting socks…', 'Sorting the toy box…', 'Folding muslins…'],
  library: ['Collecting everything you kept…', 'Checking who loved what…', 'Counting what’s done…', 'Warming bottles…'],
  default: ['Getting things ready…', 'Counting socks…', 'Folding muslins…', 'Warming bottles…'],
};

// Background sketches — pure CSS/SVG, drawn faintly behind the star.
function MrLoadingSketch({ page }) {
  if (page === 'rooms') {
    return (
      <svg className="mrl-sketch mrl-sketch--rooms" viewBox="0 0 360 300" aria-hidden="true">
        <path className="mrl-wall" d="M40 40h210v120h50v110H40z" />
        <path className="mrl-door" d="M40 200a40 40 0 0 1 40 40" />
        <rect className="mrl-box" x="60" y="60" width="90" height="56" rx="6" style={{ animationDelay: '.6s' }} />
        <rect className="mrl-box" x="170" y="60" width="60" height="60" rx="6" style={{ animationDelay: '1s' }} />
        <rect className="mrl-box" x="190" y="200" width="90" height="60" rx="6" style={{ animationDelay: '1.4s' }} />
        <rect className="mrl-box" x="60" y="160" width="50" height="40" rx="6" style={{ animationDelay: '1.8s' }} />
      </svg>
    );
  }
  if (page === 'list' || page === 'lists' || page === 'library') {
    const n = page === 'list' ? 8 : 9;
    return (
      <div className={`mrl-sketch mrl-sketch--cards${page === 'list' ? '' : ' is-tiles'}`} aria-hidden="true">
        {Array.from({ length: n }).map((_, i) => (
          <div key={i} className="mrl-card" style={{ animationDelay: `${i * 0.18}s` }}>
            <i className="mrl-card-img" /><i className="mrl-card-l1" /><i className="mrl-card-l2" />
          </div>
        ))}
      </div>
    );
  }
  // sheets + default: rows drawing in with status chips
  const chips = ['c', 'g', 'b', '', 'c', 'g', '', 'b'];
  return (
    <div className="mrl-sketch mrl-sketch--sheet" aria-hidden="true">
      {Array.from({ length: 8 }).map((_, r) => (
        <div key={r} className="mrl-row">
          {[0, 1, 2, 3, 4].map(c => (
            <i key={c} className={`mrl-cell${c === 0 ? ' is-thumb' : ''}${c === 3 && chips[r] ? ' chip-' + chips[r] : ''}`} style={{ animationDelay: `${r * 0.28 + c * 0.06}s` }} />
          ))}
        </div>
      ))}
    </div>
  );
}

function MrLoadingStar() {
  // 6 sparkles around the star, each popping on its own beat; a slow
  // orbit of dust behind; a shine sweeping across the face of the star.
  const sparkles = [
    { x: -62, y: -30, s: 10, d: 0 }, { x: 64, y: -22, s: 8, d: .45 }, { x: 70, y: 34, s: 12, d: .9 },
    { x: -70, y: 40, s: 8, d: 1.35 }, { x: 4, y: -74, s: 9, d: 1.8 }, { x: 10, y: 76, s: 7, d: 2.25 },
  ];
  return (
    <div className="mrl-star" aria-hidden="true">
      <div className="mrl-halo" />
      <div className="mrl-orbit"><i /><i /><i /><i /><i /><i /></div>
      {sparkles.map((p, i) => (
        <span key={i} className="mrl-spark" style={{ '--x': p.x + 'px', '--y': p.y + 'px', '--s': p.s + 'px', animationDelay: p.d + 's' }} />
      ))}
      <svg className="mrl-starsvg" width="96" height="96" viewBox="0 0 90 90">
        <defs>
          <linearGradient id="mrlShine" x1="0" y1="0" x2="1" y2="0">
            <stop offset="0" stopColor="#fff" stopOpacity="0" />
            <stop offset=".5" stopColor="#fff" stopOpacity=".85" />
            <stop offset="1" stopColor="#fff" stopOpacity="0" />
          </linearGradient>
          <clipPath id="mrlClip"><path d="M45 6l11 25 27 3-20 18 6 27-24-14-24 14 6-27L7 34l27-3z" /></clipPath>
        </defs>
        <path className="mrl-starbody" d="M45 6l11 25 27 3-20 18 6 27-24-14-24 14 6-27L7 34l27-3z" />
        <rect className="mrl-shine" x="-40" y="0" width="30" height="90" fill="url(#mrlShine)" clipPath="url(#mrlClip)" />
        <circle className="mrl-eye" cx="37" cy="44" r="2.6" /><circle className="mrl-eye" cx="53" cy="44" r="2.6" />
        <path className="mrl-smile" d="M38 53q7 6 14 0" />
      </svg>
      <div className="mrl-shadow" />
    </div>
  );
}

function MrLoading({ page = 'default', size = 'full', label = null }) {
  const lines = MR_LOADING_LINES[page] || MR_LOADING_LINES.default;
  const [i, setI] = React.useState(0);
  React.useEffect(() => {
    const t = setInterval(() => setI(x => (x + 1) % lines.length), 1700);
    return () => clearInterval(t);
  }, [lines.length]);
  return (
    <div className={`mrl mrl--${size} mrl--${page}`} role="status" aria-live="polite" aria-label="Loading">
      <MrLoadingSketch page={page} />
      <div className="mrl-centre">
        <MrLoadingStar />
        <div className="mrl-line" key={i}>{label || lines[i]}</div>
      </div>
    </div>
  );
}

window.MrLoading = MrLoading;
