@extends('layouts.app', [
    'title' => 'Chat SDKs | VejalNai',
    'topbarTitle' => 'Plugins',
    'topbarSubtitle' => 'Install VejalNai chat on web, Android, iOS, Flutter, and React Native',
])

@php
    $widgetKey = $organization?->widget_public_key ?? '';
    $baseUrl = url('/');
    $embedSnippet = <<<HTML
<script
  async
  src="{$scriptUrl}"
  data-widget-key="{$widgetKey}"
  data-locale="bn">
</script>
HTML;

    $androidSnippet = <<<KOTLIN
val client = VejalNaiChatClient(
    baseUrl = "{$baseUrl}",
    widgetKey = "{$widgetKey}",
    visitorId = "customer-123",
    locale = "bn"
)

val response = client.sendMessage("delivery charge koto?")
KOTLIN;

    $iosSnippet = <<<SWIFT
let client = VejalNaiChatClient(
    baseURL: URL(string: "{$baseUrl}")!,
    widgetKey: "{$widgetKey}",
    visitorId: "customer-123",
    locale: "bn"
)

let response = try await client.sendMessage("delivery charge koto?")
SWIFT;

    $flutterSnippet = <<<DART
final response = await http.post(
  Uri.parse('{$apiUrl}'),
  headers: {'Content-Type': 'application/json'},
  body: jsonEncode({
    'widget_key': '{$widgetKey}',
    'visitor_id': 'customer-123',
    'platform': 'flutter',
    'locale': 'bn',
    'body': 'delivery charge koto?',
  }),
);
DART;

    $reactNativeSnippet = <<<JS
const response = await fetch('{$apiUrl}', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    widget_key: '{$widgetKey}',
    visitor_id: 'customer-123',
    platform: 'react-native',
    locale: 'bn',
    body: 'delivery charge koto?',
  }),
});
JS;

    $apiSnippet = <<<HTTP
POST {$apiUrl}
Content-Type: application/json

{
  "widget_key": "{$widgetKey}",
  "visitor_id": "customer-123",
  "platform": "web",
  "locale": "bn",
  "body": "delivery charge koto?"
}
HTTP;
@endphp

@section('content')
    <section class="page">
        <div class="section-header">
            <div>
                <h1>Chat SDKs</h1>
                <p class="muted" style="margin: 0;">Use one widget key across web, Android, iOS, Flutter, React Native, or direct REST integrations.</p>
            </div>
            <div style="display: flex; gap: 10px;">
                <a class="button secondary" href="{{ route('settings.appearance.edit') }}">Customize appearance</a>
                <a class="button" href="{{ route('conversations.index') }}">Open inbox</a>
            </div>
        </div>

        <div class="grid" style="grid-template-columns: minmax(0, 1.25fr) minmax(280px, 0.75fr); align-items: start;">
            <section class="panel">
                <div class="panel-header">
                    <div>
                        <h2>Implementation options</h2>
                        <span class="muted">Copy the option that matches your platform.</span>
                    </div>
                    <span @class(['badge', 'warning' => ! $organization?->widget_enabled])>
                        {{ $organization?->widget_enabled ? 'Enabled' : 'Disabled' }}
                    </span>
                </div>
                <div class="panel-body stack">
                    <label>
                        <span class="field-label">Web JavaScript embed</span>
                        <textarea class="code-box" readonly>{{ $embedSnippet }}</textarea>
                    </label>

                    <label>
                        <span class="field-label">Android Kotlin SDK</span>
                        <textarea class="code-box" readonly>{{ $androidSnippet }}</textarea>
                    </label>

                    <label>
                        <span class="field-label">iOS Swift SDK</span>
                        <textarea class="code-box" readonly>{{ $iosSnippet }}</textarea>
                    </label>

                    <label>
                        <span class="field-label">Flutter REST example</span>
                        <textarea class="code-box" readonly>{{ $flutterSnippet }}</textarea>
                    </label>

                    <label>
                        <span class="field-label">React Native REST example</span>
                        <textarea class="code-box" readonly>{{ $reactNativeSnippet }}</textarea>
                    </label>

                    <label>
                        <span class="field-label">Direct REST endpoint</span>
                        <textarea class="code-box" readonly>{{ $apiSnippet }}</textarea>
                    </label>
                </div>
            </section>

            <aside class="stack">
                <section class="card">
                    <span class="metric-label">Widget key</span>
                    <strong style="display: block; font-family: Consolas, monospace; margin-top: 10px; word-break: break-all;">{{ $widgetKey ?: 'Not generated' }}</strong>
                    <form action="{{ route('chat-widget.reset-key') }}" method="POST" style="margin-top: 12px;" data-confirm="Are you sure you want to reset the widget key? Existing SDK integrations will stop working immediately until they are updated with the new key." data-confirm-title="Reset Widget Key" data-confirm-btn="Yes, reset key" data-cancel-btn="No, cancel">
                        @csrf
                        <button type="submit" class="button secondary" style="font-size: 13px; padding: 4px 12px; min-height: 0;">Reset key</button>
                    </form>
                </section>

                <section class="card">
                    <span class="metric-label">SDK source files</span>
                    <div class="activity-row">
                        <span>Android Kotlin</span>
                        <strong>sdk/android</strong>
                    </div>
                    <div class="activity-row">
                        <span>iOS Swift</span>
                        <strong>sdk/ios</strong>
                    </div>
                    <div class="activity-row">
                        <span>Other platforms</span>
                        <strong>REST</strong>
                    </div>
                </section>

                <section class="card">
                    <span class="metric-label">Allowed origins</span>
                    @if ($organization?->widget_allowed_origins)
                        <pre style="white-space: pre-wrap;">{{ $organization->widget_allowed_origins }}</pre>
                    @else
                        <p class="muted" style="margin-bottom: 0;">All origins are currently allowed. Restrict origins before production when only approved web domains should use this widget key.</p>
                    @endif
                </section>

                <section class="card">
                    <span class="metric-label">Message flow</span>
                    <div class="activity-row">
                        <span>Client sends message</span>
                        <strong>1</strong>
                    </div>
                    <div class="activity-row">
                        <span>Bot matcher replies</span>
                        <strong>2</strong>
                    </div>
                    <div class="activity-row">
                        <span>Unknowns become handoffs</span>
                        <strong>3</strong>
                    </div>
                </section>
            </aside>
        </div>
    </section>

    <script>
        document.querySelectorAll('.code-box').forEach(box => {
            const wrapper = document.createElement('div');
            wrapper.style.position = 'relative';
            box.parentNode.insertBefore(wrapper, box);
            wrapper.appendChild(box);
            
            const btn = document.createElement('button');
            btn.type = 'button';
            btn.className = 'button secondary';
            btn.style.cssText = 'position: absolute; top: 8px; right: 8px; padding: 4px 8px; font-size: 11px; min-height: 0; z-index: 2;';
            btn.innerText = 'Copy';
            btn.onclick = () => {
                navigator.clipboard.writeText(box.value).then(() => {
                    const originalText = btn.innerText;
                    btn.innerText = 'Copied!';
                    btn.style.borderColor = 'var(--green)';
                    btn.style.color = 'var(--green)';
                    setTimeout(() => {
                        btn.innerText = originalText;
                        btn.style.borderColor = '';
                        btn.style.color = '';
                    }, 2000);
                });
            };
            wrapper.appendChild(btn);
        });
    </script>
@endsection
