/* eslint-disable */
/* =============================================================
   LoadingChartState — "chart is being generated" state
   -------------------------------------------------------------
   The ghost bodygraph draws in behind a sweeping progress ring;
   a live percentage counts up while a checklist of build steps
   completes in sequence. Surrounding skeleton cards mimic the
   overview dashboard loading. Reuses .state-* tokens.
   Props: lang, onRoute, onDone (optional — called at 100%)
   ============================================================= */
(function () {
  const { useState, useEffect, useRef } = React;

  function Skeleton({ lines = 4, title }) {
    return (
      <div className="ld-skel">
        {title && <div className="ld-skel-head"><span className="ld-skel-pill" /></div>}
        <div className="ld-skel-rows">
          {Array.from({ length: lines }).map((_, i) => (
            <span key={i} className="ld-skel-row" style={{ width: `${92 - (i % 3) * 16}%` }} />
          ))}
        </div>
      </div>
    );
  }

  window.LoadingChartState = function LoadingChartState({ lang = "ar", onRoute, onDone }) {
    const ar = lang === "ar";
    const [pct, setPct] = useState(0);
    const doneRef = useRef(false);

    const T = ar
      ? { title: "جارٍ تجهيز خريطتك…", sub: "يتم الآن حساب وتحليل تصميمك الفريد",
          cardTitle: "جارٍ تحميل رؤيتك الشخصية", cardSub: "قد يستغرق الأمر بضع ثوانٍ بينما نجلب ونحلّل بياناتك الفلكية للحصول على أدق النتائج.",
          steps: ["تحميل بيانات الميلاد", "رسم مخطط التصميم", "حساب النقاط والقنوات", "تحليل المراكز والطاقة"] }
      : { title: "Preparing your chart…", sub: "Calculating and analysing your unique design",
          cardTitle: "Loading your personal insight", cardSub: "This may take a few seconds while we fetch and analyse your astronomical data for the most accurate results.",
          steps: ["Loading birth data", "Drawing the design map", "Computing gates & channels", "Analysing centers & energy"] };

    // progress engine — eases up, loops for the demo/state view
    useEffect(() => {
      let raf, start = performance.now();
      const DUR = 5200;
      const tick = (now) => {
        let t = ((now - start) % (DUR + 1100)) / DUR;
        if (t > 1) t = 1; // hold at 100% during the tail pause
        const eased = t < 1 ? 1 - Math.pow(1 - t, 2.2) : 1;
        setPct(Math.round(eased * 100));
        if (eased >= 1 && !doneRef.current) { doneRef.current = true; onDone && onDone(); }
        if (eased < 1) doneRef.current = false;
        raf = requestAnimationFrame(tick);
      };
      raf = requestAnimationFrame(tick);
      return () => cancelAnimationFrame(raf);
    }, []);

    // ring geometry
    const R = 132, C = 2 * Math.PI * R;
    const off = C * (1 - pct / 100);
    const stepState = (i) => {
      const per = 100 / T.steps.length;
      if (pct >= (i + 1) * per) return "done";
      if (pct >= i * per) return "active";
      return "wait";
    };

    return (
      <div className="ld-state" data-screen-label="state chart-loading">
        {/* side skeletons (left in DOM) */}
        <div className="ld-side ld-side-a">
          <Skeleton title lines={5} />
          <Skeleton title lines={4} />
        </div>

        {/* center hero */}
        <div className="ld-hero">
          <h1 className="ld-title">{T.title}</h1>
          <p className="ld-sub">{T.sub}</p>

          <div className="ld-ring-wrap">
            <div className="ld-ghost">{window.GhostBodygraph && <window.GhostBodygraph />}</div>
            <svg className="ld-ring" viewBox="0 0 300 300" aria-hidden="true">
              <defs>
                <linearGradient id="ld-grad" x1="0" y1="0" x2="1" y2="1">
                  <stop offset="0%" stopColor="#62DDFF" />
                  <stop offset="100%" stopColor="#C084FF" />
                </linearGradient>
              </defs>
              <circle cx="150" cy="150" r={R} fill="none" stroke="rgba(150,165,235,0.12)" strokeWidth="4" />
              <circle cx="150" cy="150" r={R} fill="none" stroke="url(#ld-grad)" strokeWidth="4"
                strokeLinecap="round" strokeDasharray={C} strokeDashoffset={off}
                transform="rotate(-90 150 150)"
                style={{ filter: "drop-shadow(0 0 6px rgba(138,92,255,0.6))", transition: "stroke-dashoffset .2s linear" }} />
            </svg>
            <span className="ld-spark" style={{ "--ang": `${(pct / 100) * 360}deg` }} />
          </div>

          <div className="ld-pct">{pct}<small>%</small></div>

          <div className="ld-card">
            <div className="ld-card-h">{window.Icon && <Icon.sparkle size={16} />}<strong>{T.cardTitle}</strong></div>
            <p className="ld-card-sub">{T.cardSub}</p>
            <ul className="ld-steps">
              {T.steps.map((s, i) => {
                const st = stepState(i);
                return (
                  <li key={i} className={`ld-step ${st}`}>
                    <span className="ld-step-ic">
                      {st === "done" ? "✓" : st === "active" ? <span className="ld-spin" /> : ""}
                    </span>
                    <span className="ld-step-label">{s}</span>
                  </li>
                );
              })}
            </ul>
          </div>
        </div>

        {/* side skeletons (right in DOM) */}
        <div className="ld-side ld-side-b">
          <Skeleton title lines={5} />
          <Skeleton title lines={4} />
        </div>
      </div>
    );
  };
})();
