'use client';

/**
 * Quick-Reference-Modal für die Shop-Integration (Phase 5).
 *
 * Zeigt die wichtigsten Snippets pro Workspace zum direkten Copy-Paste an den
 * Shop-Entwickler. Vollständige Doku liegt in `docs/shop-integration-guide.md`
 * im Repo — wird im Footer verlinkt.
 *
 * Modal hat 5 Tabs: Snippet, Markup, Webhook, Conversion-Pixel, Checklist.
 * Im Webhook-Tab gibt es 3 Sprach-Sub-Tabs (Node.js, Python, curl). Das
 * PHP-Beispiel steht in der vollständigen Doku — würde lokale Security-Hooks
 * triggern und ist im Modal nicht zwingend nötig.
 */

import { useEffect, useState } from 'react';
import {
  X,
  Copy,
  Check,
  Globe,
  Webhook,
  MousePointerClick,
  BadgeEuro,
  CheckCircle2,
  FileText,
  ExternalLink,
} from 'lucide-react';
import { cn } from '@/lib/utils';

type ModalTab = 'snippet' | 'markup' | 'webhook' | 'conversion' | 'checklist';
type WebhookLang = 'node' | 'python' | 'curl';

export interface ShopIntegrationModalProps {
  open: boolean;
  onClose: () => void;
  workspaceSlug: string;
  brandName: string;
}

function getOrigin(): string {
  if (typeof window === 'undefined') return 'https://kompassmail.in3ttt.com';
  return window.location.origin;
}

export function ShopIntegrationModal({ open, onClose, workspaceSlug, brandName }: ShopIntegrationModalProps) {
  const [tab, setTab] = useState<ModalTab>('snippet');
  const [webhookLang, setWebhookLang] = useState<WebhookLang>('node');
  const [copiedKey, setCopiedKey] = useState<string | null>(null);

  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  async function copy(text: string, key: string) {
    try {
      await navigator.clipboard.writeText(text);
      setCopiedKey(key);
      setTimeout(() => setCopiedKey((cur) => (cur === key ? null : cur)), 2000);
    } catch {
      // Clipboard nicht verfügbar — User kann immer noch manuell kopieren
    }
  }

  if (!open) return null;

  const origin = getOrigin();
  const snippetCode = `<script src="${origin}/mf-track.js" data-workspace="${workspaceSlug}" defer></script>`;
  const webhookUrl = `${origin}/api/track/webhook/${workspaceSlug}`;
  const conversionPixelExample = `<script>
  (function () {
    var url = new URL(location.href);
    var r = url.searchParams.get('mf_rcp');
    if (r) {
      var img = new Image();
      img.src = '${origin}/api/track/conversion'
              + '?r=' + encodeURIComponent(r)
              + '&kind=order'
              + '&value=2990';
    }
  })();
</script>`;

  return (
    <div className="fixed inset-0 z-[60] flex" role="dialog" aria-modal="true">
      <div onClick={onClose} className="flex-1 bg-zinc-900/50 backdrop-blur-sm" aria-hidden="true" />
      <div className="flex h-full w-full max-w-[760px] flex-col overflow-hidden bg-white shadow-2xl dark:bg-zinc-950">
        {/* Header */}
        <div className="flex items-start justify-between gap-3 border-b border-zinc-200 px-5 py-4 dark:border-zinc-800">
          <div>
            <h2 className="text-lg font-semibold text-zinc-900 dark:text-zinc-100">
              Shop-Integrations-Anleitung
            </h2>
            <p className="mt-0.5 text-xs text-zinc-500">
              Quick-Reference für <strong>{brandName}</strong> · Workspace-Slug <code className="rounded bg-zinc-100 px-1 dark:bg-zinc-800">{workspaceSlug}</code>
            </p>
          </div>
          <button
            type="button"
            onClick={onClose}
            className="rounded-md p-1 text-zinc-500 transition hover:bg-zinc-100 dark:hover:bg-zinc-800"
            aria-label="Schließen"
          >
            <X className="h-4 w-4" />
          </button>
        </div>

        {/* Tab-Switcher */}
        <nav className="flex border-b border-zinc-200 px-4 dark:border-zinc-800">
          <TabBtn active={tab === 'snippet'} onClick={() => setTab('snippet')} icon={<Globe className="h-3.5 w-3.5" />} label="Snippet" />
          <TabBtn active={tab === 'markup'} onClick={() => setTab('markup')} icon={<MousePointerClick className="h-3.5 w-3.5" />} label="Markup-Events" />
          <TabBtn active={tab === 'webhook'} onClick={() => setTab('webhook')} icon={<Webhook className="h-3.5 w-3.5" />} label="Webhook" />
          <TabBtn active={tab === 'conversion'} onClick={() => setTab('conversion')} icon={<BadgeEuro className="h-3.5 w-3.5" />} label="Conversion-Pixel" />
          <TabBtn active={tab === 'checklist'} onClick={() => setTab('checklist')} icon={<CheckCircle2 className="h-3.5 w-3.5" />} label="Checklist" />
        </nav>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-5">
          {tab === 'snippet' && <SnippetTab snippet={snippetCode} onCopy={copy} copiedKey={copiedKey} />}
          {tab === 'markup' && <MarkupTab onCopy={copy} copiedKey={copiedKey} />}
          {tab === 'webhook' && (
            <WebhookTab
              webhookUrl={webhookUrl}
              workspaceSlug={workspaceSlug}
              lang={webhookLang}
              setLang={setWebhookLang}
              onCopy={copy}
              copiedKey={copiedKey}
            />
          )}
          {tab === 'conversion' && <ConversionTab pixelExample={conversionPixelExample} onCopy={copy} copiedKey={copiedKey} />}
          {tab === 'checklist' && <ChecklistTab />}
        </div>

        {/* Footer */}
        <div className="border-t border-zinc-200 bg-zinc-50/50 px-5 py-3 dark:border-zinc-800 dark:bg-zinc-900/50">
          <div className="flex items-center justify-between text-xs">
            <span className="text-zinc-500">Vollständige Doku mit PHP-Beispiel, Troubleshooting und Referenz:</span>
            <code className="flex items-center gap-1 rounded bg-zinc-100 px-2 py-1 font-mono text-[10px] text-zinc-700 dark:bg-zinc-800 dark:text-zinc-300">
              <FileText className="h-3 w-3" />
              docs/shop-integration-guide.md
            </code>
          </div>
        </div>
      </div>
    </div>
  );
}

function TabBtn({
  active,
  onClick,
  icon,
  label,
}: {
  active: boolean;
  onClick: () => void;
  icon: React.ReactNode;
  label: string;
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={cn(
        'inline-flex items-center gap-1.5 border-b-2 px-3 py-2.5 text-xs font-medium transition',
        active
          ? 'border-zinc-900 text-zinc-900 dark:border-zinc-100 dark:text-zinc-100'
          : 'border-transparent text-zinc-500 hover:text-zinc-700 dark:hover:text-zinc-300',
      )}
    >
      {icon}
      {label}
    </button>
  );
}

function CodeBlock({
  code,
  language,
  copyKey,
  onCopy,
  copiedKey,
}: {
  code: string;
  language: string;
  copyKey: string;
  onCopy: (text: string, key: string) => void;
  copiedKey: string | null;
}) {
  return (
    <div className="relative">
      <pre className="overflow-x-auto rounded-md border border-zinc-200 bg-zinc-50 p-3 font-mono text-[11px] leading-relaxed text-zinc-800 dark:border-zinc-700 dark:bg-zinc-950 dark:text-zinc-300">
        <code>{code}</code>
      </pre>
      <div className="absolute right-2 top-2 flex items-center gap-1">
        <span className="rounded bg-zinc-200 px-1.5 py-0.5 font-mono text-[9px] uppercase text-zinc-600 dark:bg-zinc-800 dark:text-zinc-400">
          {language}
        </span>
        <button
          type="button"
          onClick={() => onCopy(code, copyKey)}
          className="inline-flex items-center gap-1 rounded bg-white px-1.5 py-0.5 text-[10px] text-zinc-700 shadow-sm hover:bg-zinc-50 dark:bg-zinc-900 dark:text-zinc-300 dark:hover:bg-zinc-800"
        >
          {copiedKey === copyKey ? <Check className="h-3 w-3" /> : <Copy className="h-3 w-3" />}
          {copiedKey === copyKey ? 'Kopiert' : 'Kopieren'}
        </button>
      </div>
    </div>
  );
}

function Section({ title, hint, children }: { title: string; hint?: string; children: React.ReactNode }) {
  return (
    <section className="mb-5">
      <h3 className="text-sm font-semibold text-zinc-900 dark:text-zinc-100">{title}</h3>
      {hint && <p className="mt-0.5 text-[11px] text-zinc-500">{hint}</p>}
      <div className="mt-2">{children}</div>
    </section>
  );
}

function SnippetTab({
  snippet,
  onCopy,
  copiedKey,
}: {
  snippet: string;
  onCopy: (text: string, key: string) => void;
  copiedKey: string | null;
}) {
  return (
    <>
      <Section title="Step 1: mf-track.js einbinden" hint="Auf jeder Shop-Seite vor </body>. defer ist Pflicht. Genau ein Snippet pro Seite.">
        <CodeBlock code={snippet} language="html" copyKey="snippet" onCopy={onCopy} copiedKey={copiedKey} />
      </Section>
      <Section title="Was passiert automatisch" hint="Sobald das Script lädt UND ein Newsletter-Empfänger über einen MailForge-Link auf der Seite landet:">
        <ul className="space-y-1.5 text-xs text-zinc-700 dark:text-zinc-300">
          <li>• <strong>pageview</strong> — beim DOMContentLoaded</li>
          <li>• <strong>scroll_depth</strong> — bei 25/50/75/100 % Scroll</li>
          <li>• <strong>time_on_page</strong> — beim beforeunload / Tab-Wechsel (min. 3 s)</li>
          <li>• <strong>product_view</strong> — falls JSON-LD Schema.org <code>@type:Product</code> auf der Seite ist</li>
        </ul>
      </Section>
      <Section title="Verifikation" hint="Im Inkognito-Fenster nach dem Klick auf einen Tracking-Link:">
        <ol className="ml-4 list-decimal space-y-1 text-xs text-zinc-700 dark:text-zinc-300">
          <li>DevTools → Network → Filter <code>mf-track</code> → 200 OK</li>
          <li>DevTools → Application → Cookies → <code>mf_attr</code> ist gesetzt</li>
          <li>Console: <code>window.mfTrack</code> ist eine Function</li>
        </ol>
      </Section>
    </>
  );
}

function MarkupTab({
  onCopy,
  copiedKey,
}: {
  onCopy: (text: string, key: string) => void;
  copiedKey: string | null;
}) {
  const examples = {
    productView: `<a href="/products/abc-123"
   data-mf-event="product_view"
   data-mf-product-id="abc-123">
  Produkt ansehen
</a>`,
    addToCart: `<button data-mf-event="add_to_cart"
        data-mf-product-id="abc-123"
        data-mf-value="2990">
  In den Warenkorb
</button>`,
    quoteForm: `<form action="/api/quote" method="POST" data-mf-event="quote_form">
  <!-- Form-Felder -->
  <button type="submit">Angebot anfordern</button>
</form>`,
    manual: `// Manuelles Tracking via JS-API:
window.mfTrack('add_to_cart', { productId: 'abc-123', value: 2990 });
window.mfTrack('custom', { meta: { name: 'brochure_download' } });`,
  };

  return (
    <>
      <Section title="product_view — Produktseite angesehen" hint="Klick auf den Link triggert Event UND folgt normal dem Link.">
        <CodeBlock code={examples.productView} language="html" copyKey="product-view" onCopy={onCopy} copiedKey={copiedKey} />
      </Section>
      <Section title="add_to_cart — In den Warenkorb" hint="data-mf-value in EUR-Cent (2990 = 29,90 €).">
        <CodeBlock code={examples.addToCart} language="html" copyKey="add-to-cart" onCopy={onCopy} copiedKey={copiedKey} />
      </Section>
      <Section title="quote_form — Angebotsformular" hint="Listener läuft auf submit-Event bevor Browser navigiert.">
        <CodeBlock code={examples.quoteForm} language="html" copyKey="quote-form" onCopy={onCopy} copiedKey={copiedKey} />
      </Section>
      <Section title="Manuelles JS-Tracking" hint="Für AJAX-Flows wo HTML-Attribute nicht ausreichen.">
        <CodeBlock code={examples.manual} language="javascript" copyKey="manual" onCopy={onCopy} copiedKey={copiedKey} />
      </Section>
    </>
  );
}

function WebhookTab({
  webhookUrl,
  workspaceSlug,
  lang,
  setLang,
  onCopy,
  copiedKey,
}: {
  webhookUrl: string;
  workspaceSlug: string;
  lang: WebhookLang;
  setLang: (l: WebhookLang) => void;
  onCopy: (text: string, key: string) => void;
  copiedKey: string | null;
}) {
  const langSnippets: Record<WebhookLang, string> = {
    node: `import { createHmac } from 'node:crypto';

const SECRET = process.env.MAILFORGE_WEBHOOK_SECRET!;
const ENDPOINT = '${webhookUrl}';

async function mailforgeSend(recipientId, event, extra = {}) {
  const body = JSON.stringify({ recipientId, event, ...extra });
  const signature = 'sha256=' + createHmac('sha256', SECRET).update(body).digest('hex');
  const res = await fetch(ENDPOINT, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-MailForge-Signature': signature,
    },
    body,
  });
  if (!res.ok) console.error('MailForge webhook failed:', res.status);
}`,
    python: `import hmac, hashlib, json, os, requests

SECRET   = os.environ['MAILFORGE_WEBHOOK_SECRET']
ENDPOINT = '${webhookUrl}'

def mailforge_send(recipient_id, event, **extra):
    payload = {'recipientId': recipient_id, 'event': event, **extra}
    body    = json.dumps(payload, separators=(',', ':'), ensure_ascii=False)
    signature = 'sha256=' + hmac.new(
        SECRET.encode('utf-8'),
        body.encode('utf-8'),
        hashlib.sha256,
    ).hexdigest()
    requests.post(ENDPOINT,
        data=body.encode('utf-8'),
        headers={
            'Content-Type': 'application/json',
            'X-MailForge-Signature': signature,
        },
        timeout=10)`,
    curl: `#!/usr/bin/env bash
SECRET="<64-char-hex-secret-aus-settings>"
ENDPOINT="${webhookUrl}"
BODY='{"recipientId":"<RECIPIENT_UUID>","event":"add_to_cart","value":2990}'

SIGNATURE="sha256=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$SECRET" -hex | awk '{print $2}')"

curl -sS -X POST "$ENDPOINT" \\
  -H "Content-Type: application/json" \\
  -H "X-MailForge-Signature: $SIGNATURE" \\
  --data "$BODY"`,
  };

  const langLabels: Record<WebhookLang, string> = {
    node: 'Node.js',
    python: 'Python',
    curl: 'curl / Bash',
  };

  return (
    <>
      <Section title={`Webhook-Endpoint für ${workspaceSlug}`} hint="HMAC-SHA256 mit Workspace-Secret. Pro Workspace ein eigenes Secret — siehe Onsite-Tracking-Section.">
        <CodeBlock code={`POST ${webhookUrl}`} language="http" copyKey="webhook-url" onCopy={onCopy} copiedKey={copiedKey} />
      </Section>
      <Section title="HMAC-Signing in deiner Sprache">
        <div className="mb-2 flex gap-1">
          {(['node', 'python', 'curl'] as const).map((l) => (
            <button
              key={l}
              type="button"
              onClick={() => setLang(l)}
              className={cn(
                'rounded-md px-2 py-1 text-[11px] font-medium transition',
                lang === l
                  ? 'bg-zinc-900 text-white dark:bg-zinc-100 dark:text-zinc-900'
                  : 'bg-zinc-100 text-zinc-700 hover:bg-zinc-200 dark:bg-zinc-800 dark:text-zinc-300 dark:hover:bg-zinc-700',
              )}
            >
              {langLabels[l]}
            </button>
          ))}
        </div>
        <CodeBlock code={langSnippets[lang]} language={lang === 'curl' ? 'bash' : lang} copyKey={`webhook-${lang}`} onCopy={onCopy} copiedKey={copiedKey} />
        <p className="mt-2 text-[11px] text-zinc-500">
          PHP-Beispiel mit <code>hash_hmac()</code>: siehe vollständige Doku Sektion 6.3.2.
        </p>
      </Section>
      <Section title="Response-Codes">
        <ul className="space-y-1 text-xs text-zinc-700 dark:text-zinc-300">
          <li>• <code>200</code> — Event akzeptiert, eventId im Response-Body</li>
          <li>• <code>401</code> — Signatur falsch oder Secret nicht konfiguriert</li>
          <li>• <code>404</code> — Workspace-Slug existiert nicht</li>
          <li>• <code>400</code> — recipientId oder event fehlt</li>
        </ul>
      </Section>
    </>
  );
}

function ConversionTab({
  pixelExample,
  onCopy,
  copiedKey,
}: {
  pixelExample: string;
  onCopy: (text: string, key: string) => void;
  copiedKey: string | null;
}) {
  return (
    <>
      <Section title="Conversion-Pixel auf Thank-You-Page" hint="Sofortige Conversion-Meldung — komplementär zum Cumas-Polling.">
        <CodeBlock code={pixelExample} language="html" copyKey="conversion-pixel" onCopy={onCopy} copiedKey={copiedKey} />
      </Section>
      <Section title="Parameter">
        <ul className="space-y-1 text-xs text-zinc-700 dark:text-zinc-300">
          <li>• <code>r</code> — Recipient-UUID (aus URL-Param <code>mf_rcp</code> oder <code>mf_attr</code>-Cookie)</li>
          <li>• <code>kind</code> — <code>order</code> / <code>lead</code> / <code>magic_login</code> / <code>form_submit</code></li>
          <li>• <code>value</code> — EUR-Cent oder ganze EUR (Cent empfohlen für Konsistenz)</li>
        </ul>
      </Section>
      <Section title="Recipient-ID aus Cookie (Fallback)">
        <p className="text-xs text-zinc-700 dark:text-zinc-300">
          Wenn <code>?mf_rcp=...</code> nicht in der URL ist (User hat Seiten gewechselt), lies aus dem
          <code> mf_attr</code>-Cookie das JSON-Feld <code>.r</code>. Siehe Doku Sektion 5.3.
        </p>
      </Section>
    </>
  );
}

function ChecklistTab() {
  const items = [
    'Snippet lädt im Browser (Network-Tab: mf-track.js → 200)',
    'Cookie mf_attr ist nach Klick auf Tracking-Link in DevTools sichtbar',
    'pageview-Event erscheint in MailForge → Empfänger → Drawer',
    'Click auf data-mf-event-Button landet als Event in MailForge',
    'Webhook mit korrekter HMAC-Signatur → 200',
    'Webhook mit falscher Signatur → 401',
    'Optout-Link in der Mail funktioniert (Cookie mf_track_optout=1 wird gesetzt)',
    'Browser-Console ist sauber — keine Errors',
    'GA4-Lookup zeigt Daten (falls konfiguriert)',
    'Performance — Lighthouse-Score nicht messbar verschlechtert',
  ];
  return (
    <Section title="Pre-Go-Live-Checklist" hint="Alle 10 Punkte vor dem produktiven Roll-Out abhaken:">
      <ul className="space-y-2">
        {items.map((item, i) => (
          <li key={i} className="flex items-start gap-2 text-xs text-zinc-700 dark:text-zinc-300">
            <span className="mt-0.5 inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded border border-zinc-300 text-[10px] dark:border-zinc-700">
              {i + 1}
            </span>
            <span>{item}</span>
          </li>
        ))}
      </ul>
      <div className="mt-4 flex items-start gap-2 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-[11px] text-amber-900 dark:border-amber-900/50 dark:bg-amber-950/30 dark:text-amber-200">
        <ExternalLink className="mt-0.5 h-3.5 w-3.5 shrink-0" />
        <span>
          Für vollständige Test-Anleitung mit Troubleshooting siehe <code>docs/shop-integration-guide.md</code> Sektion 9 + 10.
        </span>
      </div>
    </Section>
  );
}
