// ─── Tutorial Tour ───────────────────────────────────────────────────────────
// Lightweight step-by-step guide that highlights UI areas and shows tooltips.
// Triggered automatically on first login (profiles.tour_done = false in DB),
// and accessible any time via the user profile popover in the sidebar footer.
// Super Users can reset any user's tour_done flag from ผู้ใช้ระบบ screen.
const { useState: useState_tour, useEffect: useEffect_tour, useCallback: useCallback_tour } = React;
// Clean up legacy localStorage key if present (migrated to profiles.tour_done)
try { localStorage.removeItem("badmatch_tour_done"); } catch(_) {}

const TOUR_STEPS = [
  {
    id: "welcome",
    title: "ยินดีต้อนรับสู่ BadMatch 🏸",
    body: "ระบบจัดการก๊วนแบดมินตัน — จับคู่อัตโนมัติ สมดุลตามระดับฝีมือ หมุนเวียนยุติธรรม\n\nมาดูวิธีใช้งานเบื้องต้นกันเลย!",
    target: null, // center modal
    position: "center",
  },
  {
    id: "nav-groups",
    title: "เมนู ก๊วน 🏠",
    body: "เริ่มต้นด้วยการสร้างก๊วนของคุณที่นี่\nกดเพื่อดูก๊วนทั้งหมดและเข้าจัดการแต่ละก๊วนได้เลย",
    target: '[data-tour="nav-groups"]',
    position: "right",
  },
  {
    id: "nav-players",
    title: "เมนู ผู้เล่น 👥",
    body: "เพิ่มและจัดการผู้เล่นทั้งหมดในระบบ\nตั้งชื่อ ระดับฝีมือ เพศ และดูสถิติแต่ละคนได้",
    target: '[data-tour="nav-players"]',
    position: "right",
  },
  {
    id: "create-group",
    title: "สร้างก๊วนใหม่ ➕",
    body: "กดปุ่มนี้เพื่อสร้างก๊วนใหม่\nตั้งชื่อก๊วน เพิ่มสนาม เลือกโหมดเล่น และกำหนดตัวผู้เล่น",
    target: '[data-tour="create-group"]',
    position: "bottom",
  },
  {
    id: "nav-stats",
    title: "สถิติ & คำแนะนำ 📊",
    body: "ดูสถิติผู้เล่นรายวัน รายงานแมตช์ย้อนหลัง\nและรับคำแนะนำปรับระดับฝีมือจากผลการแข่งขัน",
    target: '[data-tour="nav-stats"]',
    position: "right",
  },
  {
    id: "match-system",
    title: "ระบบจับคู่อัตโนมัติ ⚡",
    body: "เมื่อเปิดก๊วน กดปุ่ม 'สุ่มจัดคู่' ระบบจะ:\n• เลือกคนที่เล่นน้อยสุดก่อน (ยุติธรรม)\n• ไม่ให้เล่นติดกันเกิน 2 เกม (ได้พัก)\n• จับคู่ให้ทีมสมดุลตามระดับฝีมือ",
    target: null,
    position: "center",
  },
  {
    id: "settings-tip",
    title: "ตั้งค่า Skill Gap & Balance Mode ⚙️",
    body: "ในแต่ละก๊วนสามารถปรับ:\n• Mode A: คู่ระดับใกล้เคียงกัน\n• Mode B: ผลรวมทีมสมดุล\n• Skill Gap: ช่วงระดับฝีมือที่ยอมรับได้",
    target: null,
    position: "center",
  },
  {
    id: "done",
    title: "พร้อมแล้ว! 🎉",
    body: "คุณรู้จักฟีเจอร์หลักแล้ว\nถ้าอยากดู Tutorial นี้อีกครั้งกดได้ที่ชื่อของคุณมุมล่างซ้าย (บนมือถือดูในหน้าแรก)\n\nสนุกกับการตีแบด!",
    target: null,
    position: "center",
  },
];

function TourOverlay({ onClose, step, total, stepData, onNext, onPrev }) {
  const isMobile = typeof window !== "undefined" && window.innerWidth < 600;
  const isCenter = !stepData.target || stepData.position === "center" || isMobile;
  const [targetRect, setTargetRect] = useState_tour(null);

  useEffect_tour(() => {
    if (!stepData.target) { setTargetRect(null); return; }
    const el = document.querySelector(stepData.target);
    if (!el) { setTargetRect(null); return; }
    el.scrollIntoView({ block: "nearest", behavior: "smooth" });
    // Slight delay so scrollIntoView settles before measuring
    const t = setTimeout(() => {
      const r = el.getBoundingClientRect();
      setTargetRect(r);
    }, 120);
    return () => clearTimeout(t);
  }, [stepData.target]);

  // Compute card style — for mobile always center
  const cardStyle = (!isCenter && targetRect)
    ? tourCardPosition(targetRect, stepData.position)
    : {};
  const useCenterClass = isCenter || !targetRect || Object.keys(cardStyle).length === 0;

  return (
    <div className="tour-overlay" onClick={e => e.target === e.currentTarget && onClose()}>
      {/* Spotlight highlight around target element */}
      {targetRect && (
        <div className="tour-spotlight" style={{
          top:    targetRect.top    - 6,
          left:   targetRect.left   - 6,
          width:  targetRect.width  + 12,
          height: targetRect.height + 12,
        }} />
      )}

      {/* Tooltip card */}
      <div className={`tour-card ${useCenterClass ? "tour-card-center" : "tour-card-anchored"}`}
           style={cardStyle}>
        <div className="tour-step-count">{step + 1} / {total}</div>
        <div className="tour-title">{stepData.title}</div>
        <div className="tour-body">{stepData.body}</div>
        <div className="tour-actions">
          <button className="btn sm" onClick={onClose}>ข้าม</button>
          <div className="row gap-2">
            {step > 0 && <button className="btn sm" onClick={onPrev}>← ก่อนหน้า</button>}
            {step < total - 1
              ? <button className="btn primary sm" onClick={onNext}>ถัดไป →</button>
              : <button className="btn primary sm" onClick={onClose}>เริ่มใช้งาน 🏸</button>}
          </div>
        </div>
        {/* Progress dots */}
        <div className="tour-dots">
          {Array.from({length: total}).map((_, i) => (
            <span key={i} className={`tour-dot ${i === step ? "active" : ""}`} />
          ))}
        </div>
      </div>
    </div>
  );
}

function tourCardPosition(rect, position) {
  const GAP = 14;
  const CARD_W = Math.min(300, window.innerWidth - 32);
  const CARD_H_EST = 220; // estimated card height for collision avoidance
  const vw = window.innerWidth;
  const vh = window.innerHeight;

  // On narrow screens (mobile), always center — no horizontal room to anchor
  if (vw < 600) return {};

  let top, left;

  if (position === "right") {
    top = rect.top;
    left = rect.right + GAP;
    // Overflow right → try left side
    if (left + CARD_W > vw - 10) left = rect.left - CARD_W - GAP;
  } else if (position === "bottom") {
    top = rect.bottom + GAP;
    left = rect.left;
    // Overflow bottom → place above
    if (top + CARD_H_EST > vh - 20) top = rect.top - CARD_H_EST - GAP;
  } else if (position === "left") {
    top = rect.top;
    left = rect.left - CARD_W - GAP;
    // Overflow left → try right
    if (left < 10) left = rect.right + GAP;
  }

  // Clamp to viewport
  top  = Math.max(16, Math.min(top,  vh - CARD_H_EST - 16));
  left = Math.max(16, Math.min(left, vw - CARD_W - 16));

  return { position: "fixed", top, left, width: CARD_W };
}

function TourLauncher({ onStart }) {
  return (
    <button className="tour-launch-btn" onClick={onStart} title="เปิด Tutorial">
      <Icon name="help" size={15} />
      <span>ดูวิธีใช้งาน</span>
    </button>
  );
}

// Hook: manages tour state — reads/writes profiles.tour_done via store.
// Pass the store object so it can call setTourDone.
function useTour(store) {
  const [open, setOpen] = useState_tour(false);
  const [step, setStep] = useState_tour(0);

  // Auto-launch ONLY when there's a logged-in user whose tour_done is false.
  // Critical: must gate on currentUser — otherwise the 800ms timer is scheduled
  // while still on the login screen (currentUser=null → tourDone defaults false),
  // fires after the user spends >800ms typing credentials, and the tour pops up
  // even for users who already completed it (tour_done=true in DB).
  // Also force-close on logout / no-user so a stale open state can't leak through.
  useEffect_tour(() => {
    if (!store || !store.currentUser) { setOpen(false); return; }
    // Don't launch over the forced password-change gate; wait until it's cleared.
    if (store.mustChangePassword) return;
    if (!store.tourDone) {
      const t = setTimeout(() => setOpen(true), 800);
      return () => clearTimeout(t);
    }
  }, [store?.tourDone, store?.currentUser?.id, store?.mustChangePassword]);

  const start = useCallback_tour(() => { setStep(0); setOpen(true); }, []);
  const close = useCallback_tour(() => {
    setOpen(false);
    if (store) store.setTourDone(true);
  }, [store]);
  const next = useCallback_tour(() => setStep(s => Math.min(s + 1, TOUR_STEPS.length - 1)), []);
  const prev = useCallback_tour(() => setStep(s => Math.max(s - 1, 0)), []);

  return { open, step, start, close, next, prev };
}

Object.assign(window, { TourOverlay, TourLauncher, useTour, TOUR_STEPS });
