// Tutorial — Interactive Spotlight Tour
// Karartma overlay + parlatılmış spotlight + Liquid Glass tooltip
// 12 adım (window.TUTORIAL_STEPS) + final pratik senaryo modal
//
// Klavye: → / Enter (ileri) · ← (geri) · Esc (atla onayı)
// Auto-positioning: spotlight target rect → tooltip preferred side fallback chain
// ResizeObserver + scroll listener: viewport değişikliklerinde pozisyon güncellenir

const { useState, useEffect, useRef, useCallback, useLayoutEffect } = React;

// ─── Tooltip Position Hesaplama ─────────────────────────────────
// Tercih sırası: preferred → diğer 3 yön. Tooltip viewport içinde kalmalı.
function computeTooltipPosition(spot, tooltipSize, preferred = 'right', viewport) {
  const margin = 20;
  const tw = tooltipSize.width || 380;
  const th = tooltipSize.height || 240;
  const vw = viewport.width;
  const vh = viewport.height;

  const cx = spot.x + spot.width / 2;
  const cy = spot.y + spot.height / 2;

  const candidates = {
    right: () => ({
      left: spot.x + spot.width + margin,
      top: cy - th / 2,
      arrow: 'left',
      fits: spot.x + spot.width + margin + tw < vw - 8,
    }),
    left: () => ({
      left: spot.x - margin - tw,
      top: cy - th / 2,
      arrow: 'right',
      fits: spot.x - margin - tw > 8,
    }),
    bottom: () => ({
      left: cx - tw / 2,
      top: spot.y + spot.height + margin,
      arrow: 'top',
      fits: spot.y + spot.height + margin + th < vh - 8,
    }),
    top: () => ({
      left: cx - tw / 2,
      top: spot.y - margin - th,
      arrow: 'bottom',
      fits: spot.y - margin - th > 8,
    }),
  };

  const order = [preferred, 'right', 'bottom', 'left', 'top'].filter(
    (v, i, arr) => arr.indexOf(v) === i
  );

  for (const dir of order) {
    const c = candidates[dir]?.();
    if (c?.fits) {
      // Viewport sınırlarına clamp
      c.left = Math.max(8, Math.min(c.left, vw - tw - 8));
      c.top  = Math.max(8, Math.min(c.top,  vh - th - 8));
      return c;
    }
  }

  // Fallback: viewport ortası
  return {
    left: Math.max(8, Math.min(cx - tw / 2, vw - tw - 8)),
    top:  Math.max(8, Math.min(cy - th / 2, vh - th - 8)),
    arrow: 'none',
  };
}

// ─── Tooltip Component ───────────────────────────────────────────
const TutorialTooltip = React.forwardRef(({ step, stepIdx, totalSteps, position, onPrev, onNext, onSkipRequest }, ref) => {
  const isFirst = stepIdx === 0;
  const isLast  = stepIdx === totalSteps - 1;

  const progressPct = ((stepIdx + 1) / totalSteps) * 100;
  const tooltipStyle = position
    ? { left: position.left, top: position.top, ['--tt-progress']: `${progressPct}%` }
    : { display: 'none' };

  return (
    <div
      ref={ref}
      className="tutorial-tooltip"
      data-arrow={position?.arrow || 'none'}
      style={tooltipStyle}
    >
      <div className="tutorial-progress">
        <div className="tutorial-progress-dots">
          {Array.from({ length: totalSteps }).map((_, i) => (
            <span
              key={i}
              className={`tutorial-progress-dot ${i < stepIdx ? 'done' : i === stepIdx ? 'current' : ''}`}
            />
          ))}
        </div>
        <span className="tutorial-counter">Adım {stepIdx + 1} / {totalSteps}</span>
      </div>

      <div className="tutorial-icon" aria-hidden="true">{step.icon}</div>
      <h3 className="tutorial-h3">{step.title}</h3>
      <p className="tutorial-body">{step.body}</p>

      {step.example && (
        <div className="tutorial-example">
          <span className="tip-icon">💡</span>
          <span>{step.example}</span>
        </div>
      )}

      <div className="tutorial-actions">
        <button className="tutorial-btn" onClick={onPrev} disabled={isFirst}>
          ← Geri
        </button>
        <button className="tutorial-btn primary" onClick={onNext}>
          {isLast ? 'Bitir →' : 'İleri →'}
        </button>
        <span className="tutorial-skip" onClick={onSkipRequest}>
          Turu atla →
        </span>
      </div>
    </div>
  );
});

// ─── Skip Confirm Dialog ─────────────────────────────────────────
const SkipConfirm = ({ onCancel, onConfirm }) => (
  <div className="tutorial-skip-confirm" onClick={onCancel}>
    <div className="tutorial-skip-card" onClick={(e) => e.stopPropagation()}>
      <h3>Turu atlamak istediğine emin misin?</h3>
      <p>Cockpit'i tanımak ileride zaman kazandırır. Ama istersen daha sonra Settings'ten tekrar açabilirsin.</p>
      <div className="actions">
        <button className="tutorial-btn" onClick={onCancel}>Devam et</button>
        <button className="tutorial-btn primary" onClick={onConfirm}>Atla</button>
      </div>
    </div>
  </div>
);

// ─── Senaryo Modal (Adım 12) ─────────────────────────────────────
const TutorialScenario = ({ step, stepIdx, totalSteps, onComplete }) => {
  // Klavye: Enter → complete
  useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'Enter' || e.key === 'ArrowRight') {
        e.preventDefault();
        onComplete();
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onComplete]);

  return (
    <div className="tutorial-scenario">
      <div className="tutorial-scenario-card">
        <div className="scenario-progress">
          <span className="left">✦ Pratik Örnek</span>
          <span>Adım {stepIdx + 1} / {totalSteps}</span>
        </div>
        <h1 className="scenario-h1">{step.title}</h1>
        {step.subtitle && <p className="scenario-sub">{step.subtitle}</p>}

        <div className="scenario-timeline">
          {step.events.map((e, i) => (
            <div key={i} className="scenario-event">
              <div className="scenario-event-time">
                <span aria-hidden="true">⌚</span>
                <span>{e.time}</span>
                <span className="icon" aria-hidden="true">·</span>
                <span className="icon" aria-hidden="true">{e.icon}</span>
              </div>
              <div className="scenario-event-body">{e.body}</div>
            </div>
          ))}
        </div>

        <div className="scenario-summary">
          <span className="icon" aria-hidden="true">📍</span>
          <span>{step.summary}</span>
        </div>

        <div className="scenario-final">{step.final}</div>

        <button className="scenario-cta" onClick={onComplete} autoFocus>
          <span>{step.ctaLabel}</span>
          <span aria-hidden="true">→</span>
        </button>
      </div>
    </div>
  );
};

// ─── DEV Skip Toolbar ─────────────────────────────────────────────
// Sadece **dev mode**'da görünür. Prod'da Babam görmez.
// Aktif etmek için: URL ?dev=1 (sessionStorage'da tab-scoped tutulur, localStorage'a YAZMAZ).
const isDevMode = () => {
  try {
    if (window.KW_IS_DEV === true) return true;
    if (sessionStorage.getItem('kw_dev_mode') === '1') return true;
    if (typeof location !== 'undefined' && new URLSearchParams(location.search).has('dev')) {
      // ?dev=1 geldiyse session'da kaydet (tab-scoped — Babam'ın normal link'i etkilenmez)
      sessionStorage.setItem('kw_dev_mode', '1');
      return true;
    }
  } catch {}
  return false;
};

const DevSkipToolbar = ({ onSkipOne, onSkipAll, onSkipAllStages }) => {
  if (!isDevMode()) return null;
  return (
    <div className="tutorial-dev-toolbar">
      <span className="label">DEV</span>
      <button className="tutorial-dev-btn" onClick={onSkipOne} title="Sıradaki adıma geç">
        Skip 1 →
      </button>
      <button className="tutorial-dev-btn danger" onClick={onSkipAll} title="Tüm tutorial'ı bitir">
        Skip All ⏭
      </button>
      <button className="tutorial-dev-btn danger" onClick={onSkipAllStages} title="Tutorial + Onboarding'i bitir, direkt Cockpit'e">
        Bitir + Cockpit ⤳
      </button>
    </div>
  );
};

// ─── Main TutorialOverlay ────────────────────────────────────────
const TutorialOverlay = ({ onComplete, onSkip, currentView, onSetView, onSkipAllStages }) => {
  const [stepIdx, setStepIdx] = useState(0);
  const [spotlight, setSpotlight] = useState(null);  // { x, y, width, height, radius }
  const [tooltipPos, setTooltipPos] = useState(null);
  const [skipOpen, setSkipOpen] = useState(false);
  const tooltipRef = useRef(null);
  const targetElRef = useRef(null);
  const rafRef = useRef(0);
  const retryRef = useRef(null);   // Retry timeout cleanup

  const steps = window.TUTORIAL_STEPS || [];
  const totalSteps = steps.length;
  const step = steps[stepIdx];

  // ─── Adım gerektirdiği view'a otomatik geçiş ──────────────────
  useEffect(() => {
    if (!step || step.requiresView == null) return;
    if (currentView !== step.requiresView && onSetView) {
      onSetView(step.requiresView);
    }
  }, [stepIdx]);

  // ─── Spotlight + tooltip pozisyon hesaplama ────────────────────
  // Retry: Cockpit/Sidebar henüz mount olmamışsa target bulunamayabilir.
  // View change sonrası React'ın commit etmesi için biraz beklemek gerek.
  // 12x60ms retry (toplam 720ms) — agresif retry, görünene kadar.
  const updatePosition = useCallback((retryCount = 0) => {
    if (!step) return;
    if (step.type === 'scenario') {
      setSpotlight(null);
      setTooltipPos(null);
      return;
    }

    const el = document.querySelector(step.targetSelector);
    if (!el) {
      // Cockpit bootstrap + backend init için cömert retry: 40 × 100ms = 4 saniye
      // Patron yavaş bağlantıda olabilir, sidebar mount'u gecikebilir
      if (retryCount < 40) {
        if (retryRef.current) clearTimeout(retryRef.current);
        retryRef.current = setTimeout(() => updatePosition(retryCount + 1), 100);
        return;
      }
      // 4 saniyede bulunamadı — fallback ortada tooltip
      console.warn('[tutorial] target not found after retries:', step.targetSelector);
      setSpotlight(null);
      const vw = window.innerWidth;
      const vh = window.innerHeight;
      setTooltipPos({
        left: vw / 2 - 200,
        top:  vh / 2 - 120,
        arrow: 'none',
      });
      return;
    }

    // Element bulundu ama henüz layout olmamış olabilir (width/height = 0)
    const rect0 = el.getBoundingClientRect();
    if ((rect0.width === 0 && rect0.height === 0) && retryCount < 40) {
      if (retryRef.current) clearTimeout(retryRef.current);
      retryRef.current = setTimeout(() => updatePosition(retryCount + 1), 100);
      return;
    }

    // Hedefe tutorial-target sınıfı (drop-shadow glow için)
    if (targetElRef.current && targetElRef.current !== el) {
      targetElRef.current.classList.remove('tutorial-target');
    }
    el.classList.add('tutorial-target');
    targetElRef.current = el;

    // Viewport içine scroll — INSTANT (tutorial spotlight için smooth scroll
    // rect ölçümünü bozuyor; instant scroll → tek frame'de doğru pozisyon).
    const inViewport = rect0.top >= 80 && rect0.bottom <= window.innerHeight - 80
                    && rect0.left >= 0 && rect0.right <= window.innerWidth;
    if (!inViewport) {
      try {
        el.scrollIntoView({ behavior: 'instant', block: 'center', inline: 'nearest' });
      } catch {
        // Older browsers
        el.scrollIntoView({ block: 'center', inline: 'nearest' });
      }
    }

    // 2x RAF — instant scroll'un layout flush'ı + tooltip render commit
    cancelAnimationFrame(rafRef.current);
    rafRef.current = requestAnimationFrame(() => {
      requestAnimationFrame(() => {
        const rect = el.getBoundingClientRect();
        const padding = step.spotlightPadding ?? 8;
        const sp = {
          x: rect.x - padding,
          y: rect.y - padding,
          width: rect.width + padding * 2,
          height: rect.height + padding * 2,
          radius: step.borderRadius ?? 12,
        };
        setSpotlight(sp);

        // Tooltip pozisyonu — bir sonraki frame'de tooltip render olduktan sonra
        requestAnimationFrame(() => {
          const tip = tooltipRef.current;
          const ts = tip
            ? { width: tip.offsetWidth, height: tip.offsetHeight }
            : { width: 380, height: 260 };
          const pos = computeTooltipPosition(
            sp,
            ts,
            step.preferred || 'right',
            { width: window.innerWidth, height: window.innerHeight }
          );
          setTooltipPos(pos);
        });
      });
    });
  }, [step]);

  // Step / view değiştiğinde initial delay + 2x RAF bekleyip pozisyon güncelle.
  // Cockpit/Sidebar mount'u + CSS animations + backend bootstrap için cömert delay.
  // Sonra rect ölçümü oturmuş layout üzerinden yapılır.
  useLayoutEffect(() => {
    let cancelled = false;
    // 350ms initial delay — Cockpit'in CSS animation'larını commit'lemesi için
    const t = setTimeout(() => {
      if (cancelled) return;
      requestAnimationFrame(() => {
        requestAnimationFrame(() => {
          if (!cancelled) updatePosition(0);
        });
      });
    }, 350);
    return () => {
      cancelled = true;
      clearTimeout(t);
    };
  }, [updatePosition, currentView]);

  // Tutorial overlay mount'unda yapay reflow tetikle — rect'ler kesinleşsin.
  // Patron'un "ekran küçülüp büyüyünce buluyor" davranışını programatik olarak yapar.
  useEffect(() => {
    const ticks = [200, 600, 1200];
    const timers = ticks.map(ms => setTimeout(() => {
      try { window.dispatchEvent(new Event('resize')); } catch {}
    }, ms));
    return () => timers.forEach(clearTimeout);
  }, []);

  // ─── Resize / scroll listener ──────────────────────────────────
  useEffect(() => {
    const onChange = () => updatePosition();
    window.addEventListener('resize', onChange);
    window.addEventListener('scroll', onChange, true);

    let ro;
    if (window.ResizeObserver) {
      ro = new ResizeObserver(onChange);
      ro.observe(document.documentElement);
    }
    return () => {
      window.removeEventListener('resize', onChange);
      window.removeEventListener('scroll', onChange, true);
      ro?.disconnect();
    };
  }, [updatePosition]);

  // ─── Cleanup target class on unmount / step change ─────────────
  useEffect(() => {
    return () => {
      if (targetElRef.current) {
        targetElRef.current.classList.remove('tutorial-target');
      }
      // Retry timeout step değişiminde temizlensin (eski step'in retry'si yeniyi etkilemesin)
      if (retryRef.current) {
        clearTimeout(retryRef.current);
        retryRef.current = null;
      }
    };
  }, [stepIdx]);

  useEffect(() => {
    return () => {
      // Total unmount cleanup
      if (targetElRef.current) {
        targetElRef.current.classList.remove('tutorial-target');
      }
      cancelAnimationFrame(rafRef.current);
      if (retryRef.current) clearTimeout(retryRef.current);
    };
  }, []);

  // ─── Klavye ────────────────────────────────────────────────────
  const next = useCallback(() => {
    if (stepIdx < totalSteps - 1) setStepIdx(stepIdx + 1);
    else onComplete();
  }, [stepIdx, totalSteps, onComplete]);

  const prev = useCallback(() => {
    if (stepIdx > 0) setStepIdx(stepIdx - 1);
  }, [stepIdx]);

  useEffect(() => {
    if (skipOpen) return;
    if (step?.type === 'scenario') return;   // senaryo kendi keybind'ı kullanır
    const onKey = (e) => {
      if (e.key === 'ArrowRight' || e.key === 'Enter') {
        e.preventDefault();
        next();
      } else if (e.key === 'ArrowLeft') {
        e.preventDefault();
        prev();
      } else if (e.key === 'Escape') {
        e.preventDefault();
        setSkipOpen(true);
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [next, prev, skipOpen, step]);

  if (!step) return null;

  // DEV: skip handlers
  const skipOneStep = () => {
    if (stepIdx < totalSteps - 1) setStepIdx(stepIdx + 1);
    else onComplete();
  };
  const skipAllSteps = () => onComplete();   // tüm tutorial'ı bitir → onboarding aşamasına
  const skipEverything = () => {             // tutorial + onboarding hepsi → cockpit
    if (typeof onSkipAllStages === 'function') onSkipAllStages();
    else onComplete();                       // fallback
  };

  // Senaryo tipindeyse full screen modal render
  if (step.type === 'scenario') {
    return (
      <>
        <TutorialScenario
          step={step}
          stepIdx={stepIdx}
          totalSteps={totalSteps}
          onComplete={onComplete}
        />
        <DevSkipToolbar
          onSkipOne={skipOneStep}
          onSkipAll={skipAllSteps}
          onSkipAllStages={skipEverything}
        />
        {skipOpen && (
          <SkipConfirm
            onCancel={() => setSkipOpen(false)}
            onConfirm={() => { setSkipOpen(false); onSkip(); }}
          />
        )}
      </>
    );
  }

  // Normal spotlight overlay
  return (
    <>
      <div className="tutorial-overlay">
        {spotlight && (
          <div
            className="tutorial-spotlight"
            style={{
              left: spotlight.x,
              top: spotlight.y,
              width: spotlight.width,
              height: spotlight.height,
              borderRadius: spotlight.radius,
            }}
          />
        )}
        <TutorialTooltip
          ref={tooltipRef}
          step={step}
          stepIdx={stepIdx}
          totalSteps={totalSteps}
          position={tooltipPos}
          onPrev={prev}
          onNext={next}
          onSkipRequest={() => setSkipOpen(true)}
        />
      </div>
      <DevSkipToolbar
        onSkipOne={skipOneStep}
        onSkipAll={skipAllSteps}
        onSkipAllStages={skipEverything}
      />
      {skipOpen && (
        <SkipConfirm
          onCancel={() => setSkipOpen(false)}
          onConfirm={() => { setSkipOpen(false); onSkip(); }}
        />
      )}
    </>
  );
};

window.TutorialOverlay = TutorialOverlay;
