/* global React, Icon, AppFieldLabel, PlugStyleWidgetPreview, getStoredWorkspaceId, useSelectedWorkspaceId, getEmbeddedBuilderDraft, saveEmbeddedBuilderDraft, getSafeEmbeddedSettings, getEmbeddedStarterList, getEmbeddedPositionLabel, getEmbeddedTemplateName, getWidgetAccentBackground, capitalizeEmbedded */
const {
  useEffect: useEffectEmbedded,
  useMemo: useMemoEmbedded,
  useState: useStateEmbedded,
} = React;

function EmbeddedChatbot() {
  const workspaceId = useSelectedWorkspaceId();
  const [settings, setSettings] = useStateEmbedded(() => getEmbeddedBuilderDraft());
  const [copied, setCopied] = useStateEmbedded(false);
  const [generated, setGenerated] = useStateEmbedded(false);
  const [isGenerating, setIsGenerating] = useStateEmbedded(false);
  const [apiError, setApiError] = useStateEmbedded('');
  const [generatedBotId, setGeneratedBotId] = useStateEmbedded(settings.editingBotId || '');
  const [generatedEmbedCode, setGeneratedEmbedCode] = useStateEmbedded('');

  useEffectEmbedded(() => {
    setSettings(getEmbeddedBuilderDraft());
    setCopied(false);
    setGenerated(false);
    setGeneratedBotId('');
    setGeneratedEmbedCode('');
    setApiError('');
  }, [workspaceId]);

  const starterList = useMemoEmbedded(() => getEmbeddedStarterList(settings.starters), [settings.starters]);
  const positionLabel = getEmbeddedPositionLabel(settings.position);
  const isEditing = Boolean(settings.editingBotId);

  const fallbackEmbedCode = useMemoEmbedded(() => {
    const botId = settings.editingBotId || 'pcbot_generated_after_backend';
    const embedOrigin = window.location.origin.replace(/\/+$/, '');

    return `<script\n  src="${embedOrigin}/embed.js"\n  data-bot-id="${botId}"\n  data-api-origin="${embedOrigin}"\n  async>\n</script>`;
  }, [settings.editingBotId]);

  const embedCode = generatedEmbedCode || fallbackEmbedCode;

  const updateSetting = (key, value) => {
    setCopied(false);
    setGenerated(false);
    setApiError('');
    setSettings(prev => ({ ...prev, [key]: value }));
  };

  const generateEmbedCode = async () => {
    setCopied(false);
    setGenerated(false);
    setGeneratedBotId('');
    setGeneratedEmbedCode('');
    setApiError('');

    const templateName = getEmbeddedTemplateName(settings);
    if (!templateName.trim()) {
      setApiError('Please enter a template name before generating the embed code.');
      return;
    }

    if (!settings.model.trim()) {
      setApiError('Please select a GPT model in AI Builder before generating the embed code.');
      return;
    }

    if (!settings.allowedDomains.trim()) {
      setApiError('Please add at least one allowed domain in AI Builder before generating the embed code.');
      return;
    }

    setIsGenerating(true);

    try {
      const payload = {
        ...settings,
        colorMode: 'solid',
        gradientColor: settings.color,
        chatBackgroundColor: '#000000',
        workspaceId: getStoredWorkspaceId(),
        templateName,
      };

      const endpoint = isEditing
        ? `/api/embedded-bots/${encodeURIComponent(settings.editingBotId)}`
        : '/api/embedded-bots';

      const response = await fetch(endpoint, {
        method: isEditing ? 'PATCH' : 'POST',
        credentials: 'include',
        headers: {
          'content-type': 'application/json',
        },
        body: JSON.stringify(payload),
      });

      if (response.status === 401) {
        window.location.href = (['localhost','127.0.0.1'].includes(location.hostname)?'http://localhost:8788':'https://pluginchatbot.com')+'/login.html?redirect=' + encodeURIComponent(window.location.href);
        return;
      }

      const data = await response.json();

      if (!response.ok || !data.ok) {
        throw new Error(data.error || data.details || 'Unable to generate embed code.');
      }

      const nextSettings = {
        ...settings,
        colorMode: 'solid',
        gradientColor: settings.color,
        chatBackgroundColor: '#000000',
        templateName,
        editingBotId: data.botId || settings.editingBotId || '',
      };

      setSettings(nextSettings);
      setGenerated(true);
      setGeneratedBotId(data.botId || '');
      setGeneratedEmbedCode(data.embedCode || '');
      saveEmbeddedBuilderDraft(nextSettings);
    } catch (error) {
      setApiError(error.message || 'Unable to generate embed code.');
    } finally {
      setIsGenerating(false);
    }
  };

  const copyEmbedCode = () => {
    if (navigator.clipboard && navigator.clipboard.writeText) {
      navigator.clipboard.writeText(embedCode).then(() => {
        setCopied(true);
      }).catch(() => {
        setCopied(false);
      });
    }
  };

  return (
    <main className="embedded-app-view">
      <section className="pc-section embedded-hero">
        <div className="pc-glow" style={{ width: 420, height: 420, right: '8%', top: '8%' }}></div>

        <div className="pc-container embedded-hero-grid">
          <div className="embedded-hero-copy">
            <span className="eyebrow">Embedded install</span>
            <h1>Build your chatbot widget.</h1>
            <p>
              Customize the widget and bot settings from AI Builder, then generate a clean embed code for each website template from here.
            </p>

            <div className="embedded-hero-actions">
              <a className="btn btn-primary btn-lg" href="/ai-builder">Open AI Builder</a>
              <a className="btn btn-secondary btn-lg" href="/templates">Saved Templates</a>
            </div>

            <div className="embedded-note">
              AI Builder now keeps widget appearance, conversation, website access, visitor capture, voice, OpenAI settings, and install code in one place.
            </div>
          </div>

          <HeroShowcase settings={settings} starters={starterList} positionLabel={positionLabel} />
        </div>
      </section>

      <section className="pc-section pc-section--alt" id="install">
        <div className="pc-container">
          <div className="pc-section-head">
            <span className="eyebrow">Final step</span>
            <h2>Preview & Install</h2>
            <p>
              Review the saved settings, name this website template, generate the embed code, and copy it to the target website.
            </p>
          </div>

          <div className="embedded-preview-install-wrap">
            <div className="card embedded-preview-install-card">
              <div className="embedded-preview-install-head">
                <div>
                  <span className="eyebrow">Template</span>
                  <h3>{isEditing ? 'Update this chatbot template' : 'Create a chatbot template'}</h3>
                </div>
                <div className="embedded-preview-install-actions">
                  <a className="btn btn-secondary btn-sm" href="/ai-builder">AI Builder</a>
                  <a className="btn btn-secondary btn-sm" href="/templates">Templates</a>
                  <button
                    className="btn btn-primary btn-sm"
                    type="button"
                    onClick={generateEmbedCode}
                    disabled={isGenerating}
                  >
                    {isGenerating ? 'Generating...' : isEditing ? 'Update Embed Code' : 'Generate Embed Code'}
                  </button>
                </div>
              </div>

              <div className="embedded-template-name-row">
                <InstallFormRow label="Template Name" help="Use a clear website-specific name so this template is easy to recognise in Integrations and Templates." hint="Examples: Main website, Service site, or Demo landing page.">
                  <input
                    className="embedded-input"
                    value={settings.templateName}
                    placeholder="Main website chatbot"
                    onChange={e => updateSetting('templateName', e.target.value)}
                  />
                </InstallFormRow>
                <div className="embedded-install-note">
                  <Icon name="info" size={16}/>
                  <span>{isEditing
                    ? `Editing template ID ${settings.editingBotId}. The existing embed code keeps the same bot ID.`
                    : 'A new template will be saved in Integrations after the embed code is generated.'}</span>
                </div>
              </div>

              <div className="embedded-preview-install-grid">
                <PreviewInstallPanel
                  settings={settings}
                  starters={starterList}
                  positionLabel={positionLabel}
                />

                <div className="embedded-install-column">
                  <SettingsSummary settings={settings} starters={starterList} positionLabel={positionLabel} />

                  {generatedBotId && (
                    <div className="embedded-api-feedback is-success">
                      <strong>{isEditing ? 'Template updated successfully' : 'Template generated successfully'}</strong>
                      <span>Bot ID: {generatedBotId}</span>
                    </div>
                  )}

                  {apiError && (
                    <div className="embedded-api-feedback is-error">
                      <strong>Unable to generate embed code</strong>
                      <span>{apiError}</span>
                    </div>
                  )}

                  <div className="embedded-code-box">
                    <pre>{embedCode}</pre>
                  </div>

                  <div className="embedded-code-actions">
                    <button className="btn btn-primary btn-sm" type="button" onClick={copyEmbedCode}>
                      {copied ? 'Copied' : 'Copy Code'}
                    </button>
                    <span>
                      {generated ? 'Saved in Integrations. Copy this script into the target website.' : 'Generate the code after reviewing your saved settings.'}
                    </span>
                  </div>

                  <ol className="embedded-install-steps">
                    <li>Customize settings from AI Builder.</li>
                    <li>Name the template for this specific website.</li>
                    <li>Generate and copy the embed code.</li>
                    <li>Manage all saved templates from Integrations.</li>
                  </ol>

                  <div className="embedded-backend-note">
                    PluginChatBot securely manages a private OpenAI key for each registered website. It is never stored in your browser or exposed in the embed code.
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
    </main>
  );
}

function SettingsSummary({ settings, starters, positionLabel }) {
  const domains = String(settings.allowedDomains || '')
    .split(',')
    .map(item => item.trim())
    .filter(Boolean);

  return (
    <div className="embedded-summary-grid">
      <SummaryItem label="Bot" value={settings.botName || 'PluginChatBot Assistant'} />
      <SummaryItem label="Model" value={settings.model || 'No model selected'} />
      <SummaryItem label="Reply Length" value={`${settings.maxReplyTokens || 512} tokens`} />
      <SummaryItem label="Position" value={positionLabel} />
      <SummaryItem label="Voice" value={settings.enableTts ? capitalizeEmbedded(settings.voice) : 'Off'} />
      <SummaryItem label="Visitor Capture" value={settings.visitorCaptureEnabled ? 'On' : 'Off'} />
      <SummaryItem label="Allowed Domains" value={domains.length ? domains.join(', ') : 'No domains added'} />
      <SummaryItem label="Starters" value={starters.length ? `${starters.length} configured` : 'None'} />
      <SummaryItem label="Mode" value={settings.editingBotId ? 'Update existing template' : 'Create new template'} />
    </div>
  );
}

function SummaryItem({ label, value }) {
  return (
    <div className="embedded-summary-item">
      <span>{label}</span>
      <strong>{value}</strong>
    </div>
  );
}

function InstallFormRow({ label, help, hint, children }) {
  return (
    <div className="embedded-form-row">
      <AppFieldLabel label={label} help={help}/>
      {children}
      {hint && <small>{hint}</small>}
    </div>
  );
}

function HeroShowcase({ settings, starters, positionLabel }) {
  return (
    <div className="card embedded-hero-showcase">
      <div className="embedded-showcase-topbar">
        <span></span>
        <span></span>
        <span></span>
      </div>

      <div className="embedded-showcase-dashboard">
        <div className="embedded-showcase-stat">
          <small>Model</small>
          <strong>{settings.model || 'No model selected'}</strong>
        </div>
        <div className="embedded-showcase-stat">
          <small>Position</small>
          <strong>{positionLabel}</strong>
        </div>
        <div className="embedded-showcase-stat">
          <small>Voice</small>
          <strong>{settings.enableTts ? capitalizeEmbedded(settings.voice) : 'Off'}</strong>
        </div>
      </div>

      <div className="embedded-showcase-widget">
        <div className="embedded-showcase-widget-head">
          <div>
            <strong>{settings.botName || 'PluginChatBot Assistant'}</strong>
            <span>{settings.templateName ? settings.templateName : 'Ready for install'}</span>
          </div>
          <div
            className="embedded-showcase-color"
            style={{ background: getWidgetAccentBackground(settings) }}
          ></div>
        </div>

        <div className="embedded-showcase-message">
          {settings.openingMessage || 'Hello! How can I help you today?'}
        </div>

        {starters.length > 0 && (
          <div className="embedded-showcase-starters">
            {starters.map(item => <button key={item} type="button">{item}</button>)}
          </div>
        )}

        <div className="embedded-showcase-footer">
          <span>{positionLabel}</span>
          <span>{settings.rateLimit === '0' ? 'No rate limit' : `${settings.rateLimit}/sec`}</span>
          <span>{settings.visitorCaptureEnabled ? 'Capture on' : 'Capture off'}</span>
        </div>
      </div>
    </div>
  );
}

function PreviewInstallPanel({ settings, starters, positionLabel }) {
  return (
    <PlugStyleWidgetPreview
      settings={settings}
      starters={starters}
      positionLabel={positionLabel}
      className="embedded-install-preview plug-widget-install-preview"
      compact
    />
  );
}

window.EmbeddedChatbot = EmbeddedChatbot;
