/* ClinicFlow AI — global effects: welcome loader + click sparks + empty state */

const { useState: _es, useEffect: _ee } = React;

// ---------- WELCOME LOADER ----------
function WelcomeLoader({ onDone }) {
  const [out, setOut] = _es(false);
  _ee(() => {
    const t1 = setTimeout(() => setOut(true), 3400);
    const t2 = setTimeout(() => onDone?.(), 4000);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, []);

  // Generate stable particle positions
  const particles = React.useMemo(() => (
    Array.from({ length: 24 }, (_, i) => ({
      left: (i * 37 + 13) % 100,
      top: (i * 53 + 7) % 100,
      delay: (i * 0.18) % 3.8,
      size: 1 + (i % 3),
    }))
  ), []);

  return (
    <div className={`welcome-loader ${out ? 'fade-out' : ''}`}>
      <div className="welcome-bg"/>
      <div className="welcome-grid"/>
      <div className="welcome-particles">
        {particles.map((p, i) => (
          <span key={i} style={{
            left: `${p.left}%`,
            top: `${p.top}%`,
            width: p.size + 'px',
            height: p.size + 'px',
            animationDelay: `${p.delay}s`,
          }}/>
        ))}
      </div>

      <div className="welcome-stage-wrap">
        <div className="welcome-logo">
          <div className="halo"/>
          <svg viewBox="0 0 64 64" fill="none">
            <defs>
              <linearGradient id="wlg-arc" x1="-22" y1="-18" x2="22" y2="-18" gradientUnits="userSpaceOnUse">
                <stop offset="0%"   stopColor="#C4B5FD"/>
                <stop offset="50%"  stopColor="#A78BFA"/>
                <stop offset="100%" stopColor="#7C3AED"/>
              </linearGradient>
              <linearGradient id="wlg-arc2" x1="0" y1="0" x2="0" y2="64">
                <stop offset="0%"   stopColor="#818CF8" stopOpacity="0.8"/>
                <stop offset="100%" stopColor="#7C3AED" stopOpacity="0.2"/>
              </linearGradient>
              <radialGradient id="wlg-core" cx="50%" cy="50%" r="50%">
                <stop offset="0%"   stopColor="#FFFFFF"/>
                <stop offset="100%" stopColor="#A78BFA"/>
              </radialGradient>
            </defs>

            {/* Outermost faint ring */}
            <g className="ring-outer">
              <circle cx="32" cy="32" r="28" stroke="rgba(139,92,246,0.25)" strokeWidth="1" fill="none" strokeDasharray="2 4"/>
              <circle cx="32" cy="32" r="28" stroke="rgba(167,139,250,0.5)" strokeWidth="1.2" fill="none"
                strokeDasharray="20 200" strokeLinecap="round"/>
            </g>

            {/* Middle dashed ring (reverse spin) */}
            <g className="ring-mid">
              <circle cx="32" cy="32" r="22" stroke="rgba(139,92,246,0.15)" strokeWidth="1" fill="none"/>
              <circle cx="32" cy="32" r="22" stroke="url(#wlg-arc2)" strokeWidth="1.5" fill="none"
                strokeDasharray="14 140" strokeLinecap="round"/>
            </g>

            {/* Solid main ring (drawn on entry) */}
            <circle cx="32" cy="32" r="18" stroke="#8B5CF6" strokeWidth="2.5" fill="none"
              className="ring-base" strokeLinecap="round"/>

            {/* Inner orbit arc — fast spin */}
            <g className="ring-inner-arc">
              <path d="M 14 22 A 22 22 0 0 1 50 22" stroke="url(#wlg-arc)" strokeWidth="3" strokeLinecap="round" fill="none"/>
            </g>

            {/* Satellite dot riding outer ring */}
            <g className="welcome-satellite">
              <circle cx="60" cy="32" r="2.4" fill="#A78BFA"/>
              <circle cx="60" cy="32" r="4" fill="#A78BFA" opacity="0.3"/>
            </g>

            {/* Central planet */}
            <g className="welcome-planet">
              <circle cx="32" cy="32" r="5" fill="url(#wlg-core)"/>
              <circle cx="32" cy="32" r="3" fill="white" className="welcome-core" opacity="0.9"/>
            </g>
          </svg>
        </div>

        <div className="welcome-eyebrow">By Orbis Systems</div>

        <div className="welcome-wm">
          <span className="gw1">Clinic</span><span className="gw2">Flow</span>{' '}<span className="gw3">AI</span>
        </div>

        <div className="welcome-tagline">
          <strong>Patient retention</strong>, on autopilot.
        </div>

        <div className="welcome-progress">
          <div className="welcome-progress-bar"/>
        </div>

        <div className="welcome-checks">
          <div className="welcome-check c1">
            <span className="tick"><I.check size={9} sw={3}/></span>
            <span className="lbl">Securing workspace</span>
            <span className="ms">142ms</span>
          </div>
          <div className="welcome-check c2">
            <span className="tick"><I.check size={9} sw={3}/></span>
            <span className="lbl">Connecting WhatsApp Business</span>
            <span className="ms">228ms</span>
          </div>
          <div className="welcome-check c3">
            <span className="tick"><I.check size={9} sw={3}/></span>
            <span className="lbl">Warming AI Follow-up Agent</span>
            <span className="ms">187ms</span>
          </div>
          <div className="welcome-check c4">
            <span className="tick"><I.check size={9} sw={3}/></span>
            <span className="lbl">Syncing today's appointments</span>
            <span className="ms">96ms</span>
          </div>
        </div>
      </div>

      <div className="welcome-foot">
        <span className="pulse-dot"/>
        ENTERPRISE-GRADE · COMPLIANT INFRASTRUCTURE · RAIPUR, INDIA
      </div>
    </div>
  );
}

// ---------- CLICK SPARKS ----------
// Attaches a global click listener that, when a "spark target" is clicked,
// emits 8 small purple particles that radiate out 25px and fade in 600ms.
// Target selectors include primary CTAs and brand affordances.
const SPARK_SELECTOR = [
  '.btn-primary',
  '.btn-wa',
  '.auth-submit',
  '.fab',
  '.topbar-icon-btn',
  '.nav-item',
  '.chip.active',
  '.clinic-chip-dot',
  '.menu-item',
  '.search-result',
  '.notif-item',
  '.clinic-row:not(.disabled)',
  '.page-btn.active',
  '.cal-toggle button',
  '.tab',
  '.toast-icon',
].join(',');

function initClickSparks() {
  if (window.__cf_sparks_ready) return;
  window.__cf_sparks_ready = true;

  // Disposable layer for sparks
  let layer = document.querySelector('.spark-layer');
  if (!layer) {
    layer = document.createElement('div');
    layer.className = 'spark-layer';
    document.body.appendChild(layer);
  }

  document.addEventListener('click', (e) => {
    const target = e.target.closest(SPARK_SELECTOR);
    if (!target) return;
    // Skip disabled
    if (target.disabled || target.getAttribute('aria-disabled') === 'true') return;
    spawnSparks(e.clientX, e.clientY);
  }, { passive: true });
}

function spawnSparks(x, y) {
  const layer = document.querySelector('.spark-layer');
  if (!layer) return;
  const count = 8;
  const radius = 25;
  for (let i = 0; i < count; i++) {
    const sp = document.createElement('span');
    sp.className = 'spark';
    const angle = (i / count) * Math.PI * 2 + (Math.random() - 0.5) * 0.3;
    const dist = radius + Math.random() * 6;
    sp.style.left = x + 'px';
    sp.style.top = y + 'px';
    sp.style.setProperty('--dx', Math.cos(angle) * dist + 'px');
    sp.style.setProperty('--dy', Math.sin(angle) * dist + 'px');
    sp.style.width = sp.style.height = (5 + Math.random() * 3) + 'px';
    // Slight color variance for visual life
    const hues = ['#7C3AED', '#A78BFA', '#8B5CF6', '#6366F1'];
    sp.style.background = hues[i % hues.length];
    layer.appendChild(sp);
    setTimeout(() => sp.remove(), 650);
  }
}

// ---------- EMPTY STATE ----------
function EmptyState({ icon, title, body, action }) {
  return (
    <div className="empty-state">
      <span className="empty-icon">{icon || <I.search size={22}/>}</span>
      <div>
        <h3>{title}</h3>
        {body && <p style={{ marginTop: 6 }}>{body}</p>}
      </div>
      {action}
    </div>
  );
}

Object.assign(window, { WelcomeLoader, initClickSparks, spawnSparks, EmptyState });
