// tour.jsx — TMS Email Builder onboarding tour (Driver.js v1)
(function () {
  const TOUR_KEY = 'tms_email_tour_completed_v1';
  const { useState, useEffect } = React;

  // ── Gate panel ─────────────────────────────────────────────────────────────
  function GatePanel({ onClose }) {
    const [visible, setVisible] = useState(false);

    useEffect(() => {
      const t = setTimeout(() => setVisible(true), 40);
      return () => clearTimeout(t);
    }, []);

    const dismiss = () => {
      setVisible(false);
      setTimeout(onClose, 320);
    };

    const handleDontShow = () => {
      localStorage.setItem(TOUR_KEY, '1');
      dismiss();
    };

    return (
      <div
        onClick={dismiss}
        style={{
          position: 'fixed', inset: 0, zIndex: 9990,
          background: visible ? 'rgba(0,0,0,0.38)' : 'rgba(0,0,0,0)',
          transition: 'background 0.32s ease',
          display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
        }}
      >
        <div
          onClick={e => e.stopPropagation()}
          style={{
            background: 'var(--product-surface)',
            borderRadius: '16px 16px 0 0',
            padding: '28px 28px 44px',
            width: '100%', maxWidth: 460,
            boxShadow: '0 -8px 40px rgba(0,0,0,0.18)',
            transform: visible ? 'translateY(0)' : 'translateY(100%)',
            transition: 'transform 0.32s cubic-bezier(0.4,0,0.2,1)',
          }}
        >
          <div style={{ textAlign: 'center', marginBottom: 24 }}>
            <div style={{ fontSize: 30, marginBottom: 10, color: 'var(--tms-teal-500)' }}>✓</div>
            <h3 style={{
              margin: '0 0 8px', fontSize: 18, fontWeight: 700,
              fontFamily: 'var(--font-display)', color: 'var(--product-fg)',
              letterSpacing: '-0.01em',
            }}>Got it?</h3>
            <p style={{ margin: 0, fontSize: 13.5, color: 'var(--product-fg-muted)', lineHeight: 1.55 }}>
              You can relaunch this tour or open the full documentation any time
              from the <strong style={{ color: 'var(--product-fg)' }}>Help</strong> menu in the top bar.
            </p>
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            <button onClick={handleDontShow} style={{
              background: 'var(--tms-teal-500)', color: '#fff',
              border: 'none', borderRadius: 9, padding: '12px 20px',
              fontSize: 14, fontWeight: 700, fontFamily: 'var(--font-display)',
              cursor: 'pointer', width: '100%', letterSpacing: '-0.01em',
            }}>
              Don't show this again
            </button>
            <button onClick={dismiss} style={{
              background: 'transparent', color: 'var(--product-fg-muted)',
              border: '1px solid var(--product-border)', borderRadius: 9,
              padding: '11px 20px', fontSize: 13.5, fontWeight: 500,
              fontFamily: 'var(--font-display)', cursor: 'pointer', width: '100%',
            }}>
              Maybe later
            </button>
          </div>
        </div>
      </div>
    );
  }

  // ── Gate panel mount (reuses a single root) ────────────────────────────────
  let gateContainer = null;
  let gateRoot = null;

  function mountGatePanel() {
    if (!gateContainer) {
      gateContainer = document.createElement('div');
      gateContainer.id = 'tms-tour-gate';
      document.body.appendChild(gateContainer);
    }
    if (!gateRoot) {
      gateRoot = ReactDOM.createRoot(gateContainer);
    }
    gateRoot.render(<GatePanel onClose={() => gateRoot.render(null)} />);
  }

  // ── Tour steps ─────────────────────────────────────────────────────────────
  const STEPS = [
    {
      popover: {
        title: 'Welcome to TMS Email Builder',
        description: 'Your studio for building and sending professional travel emails. This quick tour covers everything — it takes about 90 seconds.',
      },
    },
    {
      element: '.bld-sidebar',
      popover: {
        title: 'Build from blocks',
        description: 'Every email is assembled from building blocks — header, offer card, text section, image, and more. Click any block type to add it to your canvas.',
        side: 'right', align: 'start',
      },
    },
    {
      element: '#tour-sidebar-tabs',
      popover: {
        title: 'Search offers & templates',
        description: 'Switch to Holidays or Cruises to pull a live deal into your email, or load a pre-built Template to jump-start your design.',
        side: 'right', align: 'start',
      },
    },
    {
      element: '.bld-canvas-area',
      popover: {
        title: 'Your email canvas',
        description: 'This is your live preview. Click any block to select it, then edit its content and styling in the panel on the right.',
        side: 'left', align: 'start',
      },
    },
    {
      element: 'aside.bld-settings',
      popover: {
        title: 'Block settings',
        description: 'When a block is selected, its settings appear here — colours, text, images, and links. Everything is visual; no code needed.',
        side: 'left', align: 'start',
      },
    },
    {
      element: '#tour-save',
      popover: {
        title: 'Save your work',
        description: 'Your design is stored against your account. Click Save at any time to preserve your progress — you can pick up where you left off on any device.',
        side: 'bottom', align: 'end',
      },
    },
    {
      element: '#tour-send-area',
      popover: {
        title: 'Preview, export & send',
        description: 'Toggle Preview to see how your email renders. Export the HTML for any platform, or connect Campaign Monitor to create and send a campaign in one click.',
        side: 'bottom', align: 'end',
      },
    },
    {
      element: '#tour-help-btn',
      popover: {
        title: 'Need help?',
        description: 'Relaunch this tour or open the full documentation any time from the Help menu.',
        side: 'bottom', align: 'end',
      },
    },
  ];

  // ── Driver instance ────────────────────────────────────────────────────────
  function createDriver() {
    const driverFn = (window.DriverJs && window.DriverJs.driver) || window.driver;
    if (!driverFn) {
      console.warn('[TMS Tour] Driver.js not loaded — tour unavailable');
      return null;
    }

    return driverFn({
      showProgress: true,
      animate: true,
      overlayOpacity: 0.5,
      stagePadding: 10,
      stageRadius: 8,
      allowClose: true,
      nextBtnText: 'Next →',
      prevBtnText: '← Back',
      doneBtnText: 'Done',
      closeBtnText: 'Skip tour',
      onDestroyed: mountGatePanel,
      steps: STEPS,
    });
  }

  // ── Public API ─────────────────────────────────────────────────────────────
  window.launchEmailTour = function () {
    const d = createDriver();
    if (d) d.drive();
  };

  window.initEmailTour = function () {
    if (localStorage.getItem(TOUR_KEY)) return;
    // Don't interrupt users who are returning to edit a saved design
    const params = new URLSearchParams(window.location.search);
    if (params.get('design_id') || params.get('template_id')) return;
    setTimeout(window.launchEmailTour, 900);
  };
})();
