/* global React, Icon, getStoredWorkspaceId */
const {
  useEffect: useEffectExperience,
  useMemo: useMemoExperience,
  useState: useStateExperience,
} = React;

function AppInfoTip({ text, label = 'More information' }) {
  if (!text) return null;

  return (
    <span className="app-info-tip">
      <button type="button" className="app-info-button" aria-label={`${label}: ${text}`}>
        <Icon name="info" size={15} strokeWidth={1.9}/>
      </button>
      <span className="app-info-tooltip" role="tooltip">{text}</span>
    </span>
  );
}

function AppFieldLabel({ label, help, htmlFor }) {
  return (
    <span className="app-field-label-row">
      {htmlFor ? <label htmlFor={htmlFor}>{label}</label> : <span>{label}</span>}
      {help && <AppInfoTip text={help} label={label}/>}
    </span>
  );
}

const APP_TOUR_DEFINITIONS = {
  dashboard: [
    { selector: '[data-tour="dashboard"]', title: 'Dashboard', text: 'Start here for a quick view of conversations, leads, and the next setup step.' },
    { selector: '.app-workspace-button', title: 'Workspace', text: 'Use this menu to switch, create, rename, or manage the workspace currently shown across the App.' },
    { selector: '.view-head', title: 'Workspace Overview', text: 'This header shows which area you are managing and the main action for the page.' },
    { selector: '.card', title: 'Key Information', text: 'Cards keep related information together so you can scan the workspace without opening every page.' },
  ],
  conversations: [
    { selector: '[data-tour="conversations"]', title: 'Conversations', text: 'Review visitor chats, respond to handoffs, and keep important customer conversations moving.' },
    { selector: '.conversations-page, .view', title: 'Conversation Workspace', text: 'Use the conversation list, active chat, and visitor details together from this workspace.' },
  ],
  leads: [
    { selector: '[data-tour="leads"]', title: 'Leads', text: 'Captured visitor details appear here for follow-up.' },
    { selector: '.view-head', title: 'Lead Management', text: 'Use the page controls to review and manage captured enquiries.' },
  ],
  users: [
    { selector: '[data-tour="users"]', title: 'Users', text: 'Owners and admins can manage who has access to the account and its workspaces.' },
    { selector: '.view-head', title: 'Team Access', text: 'Invite users, assign access, and review roles from this page.' },
  ],
  analytics: [
    { selector: '[data-tour="analytics"]', title: 'Analytics', text: 'Use this area to understand chatbot activity and customer engagement.' },
    { selector: '.view-head', title: 'Performance Overview', text: 'The page groups the most useful performance information into readable summaries.' },
  ],
  playground: [
    { selector: '[data-tour="playground"]', title: 'Playground', text: 'Edit a saved template and test visitor capture, handoff, and chat before installing.' },
    { selector: '.playground-chat-card', title: 'Chat Surface', text: 'Send visitor-style messages to the loaded template.' },
    { selector: '.playground-inspector-panel', title: 'Run Settings', text: 'Review the instructions, guardrails, domains, and enabled tools used by the test.' },
  ],
  aiBuilder: [
    { selector: '[data-tour="aiBuilder"]', title: 'AI Builder', text: 'Build the widget, bot setup, and install code from one page.' },
    { selector: '[data-tour="ai-builder-widget"]', title: 'Widget', text: 'Adjust the brand colour, placement, identity, and conversation content.' },
    { selector: '[data-tour="ai-builder-customize"]', title: 'Customize', text: 'Manage OpenAI, website access, visitor capture, and voice settings.' },
    { selector: '[data-tour="ai-builder-knowledge-base"]', title: 'Knowledge Base', text: 'Upload approved business files and manage the knowledge used by each chatbot template.' },
    { selector: '[data-tour="ai-builder-install"]', title: 'Install', text: 'Save the template, update existing templates, and copy the embed script.' },
    { selector: '.plug-widget-live-preview', title: 'Live Preview', text: 'The preview updates as you edit and moves to the selected website position.' },
  ],
  integrations: [
    { selector: '[data-tour="integrations"]', title: 'Integrations', text: 'Connect human support, WhatsApp, and CRM tools to a saved chatbot.' },
    { selector: '.integration-template-card', title: 'Choose a Template', text: 'Integration settings are managed for the selected chatbot template.' },
    { selector: '.integration-launch-card', title: 'Open a Connection', text: 'Select a card to open its focused configuration window.' },
  ],
  templates: [
    { selector: '[data-tour="templates"]', title: 'Templates', text: 'Manage the saved chatbot configurations used across your websites.' },
    { selector: '.app-template-create', title: 'Create a Template', text: 'Start a separate chatbot configuration for another website or use case.' },
    { selector: '.app-template-card', title: 'Template Details', text: 'Expand a template to review its settings, embed code, and management actions.' },
  ],
};

function AppTourHost({ view }) {
  const steps = useMemoExperience(() => APP_TOUR_DEFINITIONS[view] || [], [view]);
  const [isOpen, setIsOpen] = useStateExperience(false);
  const [stepIndex, setStepIndex] = useStateExperience(0);

  const storageKey = useMemoExperience(() => {
    const userId = window.PluginChatBotCurrentUser?.userId || 'user';
    const workspaceId = typeof getStoredWorkspaceId === 'function' ? getStoredWorkspaceId() : 'workspace';
    return `pluginchatbot_tour:${userId}:${workspaceId}:${view}`;
  }, [view]);

  useEffectExperience(() => {
    setIsOpen(false);
    setStepIndex(0);

    if (!steps.length) return undefined;

    let hasSeenTour = false;
    try {
      hasSeenTour = window.localStorage.getItem(storageKey) === 'complete';
    } catch (error) {}

    if (hasSeenTour) return undefined;

    const timer = window.setTimeout(() => setIsOpen(true), 700);
    return () => window.clearTimeout(timer);
  }, [storageKey, steps]);

  useEffectExperience(() => {
    const startTour = event => {
      if (event.detail?.view && event.detail.view !== view) return;
      setStepIndex(0);
      setIsOpen(true);
    };

    window.addEventListener('pluginchatbot:start-tour', startTour);
    return () => window.removeEventListener('pluginchatbot:start-tour', startTour);
  }, [view]);

  useEffectExperience(() => {
    document.querySelectorAll('.is-app-tour-focus').forEach(element => {
      element.classList.remove('is-app-tour-focus');
    });

    if (!isOpen || !steps.length) return undefined;

    const currentStep = steps[stepIndex] || steps[0];
    const target = currentStep?.selector ? document.querySelector(currentStep.selector) : null;

    if (target) {
      target.classList.add('is-app-tour-focus');
      target.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'nearest' });
    }

    document.body.classList.add('has-app-page-tour');

    return () => {
      document.body.classList.remove('has-app-page-tour');
      if (target) target.classList.remove('is-app-tour-focus');
    };
  }, [isOpen, stepIndex, steps]);

  const finishTour = () => {
    try {
      window.localStorage.setItem(storageKey, 'complete');
    } catch (error) {}
    setIsOpen(false);
  };

  if (!isOpen || !steps.length) return null;

  const step = steps[stepIndex] || steps[0];
  const isLast = stepIndex >= steps.length - 1;

  return (
    <div className="app-page-tour-backdrop" role="presentation">
      <section className="app-page-tour-dialog" role="dialog" aria-modal="true" aria-labelledby="app-page-tour-title">
        <div className="app-page-tour-progress">Step {stepIndex + 1} of {steps.length}</div>
        <h2 id="app-page-tour-title">{step.title}</h2>
        <p>{step.text}</p>
        <div className="app-page-tour-dots" aria-hidden="true">
          {steps.map((item, index) => <span key={`${item.title}-${index}`} className={index === stepIndex ? 'is-active' : ''}/>) }
        </div>
        <div className="app-page-tour-actions">
          <button className="btn btn-secondary" type="button" onClick={finishTour}>Skip Tour</button>
          <div>
            {stepIndex > 0 && (
              <button className="btn btn-secondary" type="button" onClick={() => setStepIndex(index => Math.max(0, index - 1))}>Back</button>
            )}
            <button
              className="btn btn-primary"
              type="button"
              onClick={() => isLast ? finishTour() : setStepIndex(index => Math.min(steps.length - 1, index + 1))}
            >
              {isLast ? 'Finish' : 'Next'}
            </button>
          </div>
        </div>
      </section>
    </div>
  );
}

window.AppInfoTip = AppInfoTip;
window.AppFieldLabel = AppFieldLabel;
window.AppTourHost = AppTourHost;
