<?php

namespace App\Http\Controllers;

use App\Models\AppSetting;
use App\Support\MarketingDemoAgent;
use App\Support\MarketingHomeContent;
use App\Support\MarketingShellContent;
use App\Support\PrivacyPolicyContent;
use App\Support\SeoMeta;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;
use Inertia\Inertia;
use Inertia\Response;

class MarketingController
{
    public function home(): Response
    {
        $settings = AppSetting::singleton();
        $content = MarketingHomeContent::resolve($settings->marketing_home_content);

        return Inertia::render('welcome', [
            'canRegister' => Route::has('register'),
            'demoAgentId' => MarketingDemoAgent::id(),
            'content' => $content,
            'seo' => SeoMeta::for('home', [
                'faq_items' => $content['faq']['items'] ?? [],
            ]),
        ]);
    }

    public function pricing(): Response
    {
        return Inertia::render('marketing/pricing', [
            'canRegister' => Route::has('register'),
            'shell' => MarketingShellContent::resolve(),
            'brand' => $this->brand(),
            'plans' => $this->pricingPlans(),
            'matrix' => $this->pricingMatrix(),
            'faqs' => $this->pricingFaqs(),
            'contact_email' => $this->contactEmail(),
            'seo' => SeoMeta::for('pricing'),
        ]);
    }

    public function howItWorks(): Response
    {
        return Inertia::render('marketing/how-it-works', [
            'canRegister' => Route::has('register'),
            'shell' => MarketingShellContent::resolve(),
            'brand' => $this->brand(),
            'steps' => $this->howItWorksSteps(),
            'latency' => $this->latencyBudget(),
            'seo' => SeoMeta::for('how-it-works'),
        ]);
    }

    public function integrations(): Response
    {
        return Inertia::render('marketing/integrations', [
            'canRegister' => Route::has('register'),
            'shell' => MarketingShellContent::resolve(),
            'brand' => $this->brand(),
            'native' => $this->nativeIntegrations(),
            'data_sources' => $this->dataSourceIntegrations(),
            'roadmap' => $this->roadmapIntegrations(),
            'seo' => SeoMeta::for('integrations'),
        ]);
    }

    public function privacy(): Response
    {
        $settings = AppSetting::singleton();

        return Inertia::render('marketing/privacy', [
            'canRegister' => Route::has('register'),
            'shell' => MarketingShellContent::resolve(),
            'brand' => $this->brand(),
            'content' => PrivacyPolicyContent::resolve($settings->privacy_policy_content),
            'seo' => SeoMeta::for('privacy'),
        ]);
    }

    public function terms(): Response
    {
        return Inertia::render('marketing/terms', [
            'canRegister' => Route::has('register'),
            'shell' => MarketingShellContent::resolve(),
            'brand' => $this->brand(),
            'effective_date' => (string) config('branding.terms_effective_date', now()->format('F j, Y')),
            'contact_email' => $this->contactEmail(),
            'intro' => $this->termsIntro(),
            'sections' => $this->termsSections(),
            'seo' => SeoMeta::for('terms'),
        ]);
    }

    /**
     * Capture the domain and stash it in a short-lived token so the signup flow can
     * pre-fill and trigger an automatic crawl after the user finishes registration.
     */
    public function start(Request $request): RedirectResponse
    {
        $data = $request->validate(['domain' => ['required', 'url', 'max:500']]);

        $token = Str::random(32);
        Cache::put("marketing:domain:{$token}", $data['domain'], now()->addHours(2));

        // Persist on session so CreateNewUser can pick it up after registration.
        $request->session()->put('marketing.start_domain', $data['domain']);

        return redirect()->to('/register?domain='.urlencode($data['domain']).'&start_token='.$token);
    }

    private function brand(): string
    {
        return (string) config('branding.site_title', 'Pitchbar');
    }

    private function contactEmail(): string
    {
        return (string) config('mail.from.address', 'support@example.com');
    }

    /**
     * @return list<array<string, mixed>>
     */
    private function pricingPlans(): array
    {
        $brand = $this->brand();

        // Each entry has BOTH monthly + yearly prices in dollars. The
        // React pricing page renders a Monthly/Yearly toggle that
        // swaps which figure (and which CTA query string) the visitor
        // sees. Annual prices are 10× monthly = ~17% off (industry
        // standard), but admins running custom plans can override the
        // ratio per-row.
        return [
            [
                'name' => 'Free',
                'monthly_price' => 0,
                'yearly_price' => 0,
                'tagline' => 'Try it on your live site.',
                'volume' => '100 conversations / month',
                'cta_label' => 'Start free',
                'cta_href' => '/register',
                'highlight' => false,
                'features' => [
                    '1 published agent',
                    'URL + sitemap + text knowledge sources',
                    'Lead capture inbox',
                    'Slack & outgoing webhook integrations',
                    "{$brand} branding shown",
                ],
            ],
            [
                'name' => 'Standard',
                'monthly_price' => 49,
                'yearly_price' => 490,
                'tagline' => 'For real traffic.',
                'volume' => '500 conversations / month',
                'cta_label' => 'Start 14-day trial',
                'cta_href' => '/register',
                'highlight' => true,
                'features' => [
                    '5 published agents',
                    'Everything in Free, plus:',
                    'A/B testing on behavior rules',
                    'Content gap analytics',
                    'Notion + Google Doc knowledge sources',
                    'Branding removed from widget',
                    'Email support',
                ],
            ],
            [
                'name' => 'Pro',
                'monthly_price' => 249,
                'yearly_price' => 2490,
                'tagline' => 'For teams that need scale.',
                'volume' => '3,000 conversations / month',
                'cta_label' => 'Start 14-day trial',
                'cta_href' => '/register',
                'highlight' => false,
                'features' => [
                    'Unlimited agents',
                    'Everything in Standard, plus:',
                    'HubSpot + Pipedrive native sync',
                    'Higher LLM rate limits',
                    'Custom domain for the widget',
                    'Priority support, 8h SLA',
                ],
            ],
        ];
    }

    /**
     * @return list<array<string, mixed>>
     */
    private function pricingMatrix(): array
    {
        return [
            ['label' => 'Published agents', 'free' => '1', 'standard' => '5', 'pro' => 'Unlimited'],
            ['label' => 'Monthly conversations', 'free' => '100', 'standard' => '500', 'pro' => '3,000'],
            ['label' => 'Voice mic on widget', 'free' => true, 'standard' => true, 'pro' => true],
            ['label' => 'Lead capture + inbox', 'free' => true, 'standard' => true, 'pro' => true],
            ['label' => 'Persistent visitor sessions', 'free' => true, 'standard' => true, 'pro' => true],
            ['label' => 'URL / sitemap / text sources', 'free' => true, 'standard' => true, 'pro' => true],
            ['label' => 'Notion + Google Doc sources', 'free' => false, 'standard' => true, 'pro' => true],
            ['label' => 'Auto-index visited pages', 'free' => true, 'standard' => true, 'pro' => true],
            ['label' => '8 widget languages', 'free' => true, 'standard' => true, 'pro' => true],
            ['label' => 'A/B testing + content gaps', 'free' => false, 'standard' => true, 'pro' => true],
            ['label' => 'Behavior rules + CTAs', 'free' => true, 'standard' => true, 'pro' => true],
            ['label' => 'Curated answers', 'free' => true, 'standard' => true, 'pro' => true],
            ['label' => 'Branding removed', 'free' => false, 'standard' => true, 'pro' => true],
            ['label' => 'Slack + outgoing webhooks', 'free' => true, 'standard' => true, 'pro' => true],
            ['label' => 'HubSpot + Pipedrive native', 'free' => false, 'standard' => false, 'pro' => true],
            ['label' => 'Custom widget domain', 'free' => false, 'standard' => false, 'pro' => true],
            ['label' => 'Workspace members', 'free' => '2', 'standard' => '10', 'pro' => 'Unlimited'],
            ['label' => 'Support', 'free' => 'Community', 'standard' => 'Email', 'pro' => 'Priority, 8h SLA'],
        ];
    }

    /**
     * @return list<array{q: string, a: string}>
     */
    private function pricingFaqs(): array
    {
        $contact = $this->contactEmail();
        $brand = $this->brand();

        return [
            ['q' => 'What counts as a conversation?', 'a' => 'A conversation is metered the moment a visitor sends their first message. Resumed conversations within 24 hours don\'t count again. Playground / staging traffic is exempt.'],
            ['q' => 'What happens if I exceed the quota?', 'a' => 'New conversations are paused with a friendly upgrade prompt. Conversations already in progress finish normally — including human takeovers. Your widget never breaks visibly.'],
            ['q' => 'Can I cancel anytime?', 'a' => 'Yes. Cancellations take effect at the end of the billing period; you keep access until then and your data stays safe.'],
            ['q' => 'Do you offer refunds?', 'a' => "A 30-day money-back guarantee on all paid plans, no questions asked. Email {$contact}."],
            ['q' => 'Is there an Enterprise plan?', 'a' => 'Yes — custom limits, SSO, dedicated infrastructure, and a named CSM. Contact us for a quote.'],
            ['q' => 'Can I self-host?', 'a' => "{$brand} is also available as a self-hosted application via a one-time license. Same features, your infrastructure, your data."],
        ];
    }

    /**
     * @return list<array<string, mixed>>
     */
    private function howItWorksSteps(): array
    {
        return [
            [
                'number' => '01',
                'title' => 'Drop your URL',
                'duration' => '< 1 minute',
                'description' => 'Sign up, paste your website URL, and we auto-discover your sitemap and key pages (about, pricing, FAQ, docs). Tick the ones you want indexed and we crawl them in the background — respecting robots.txt, blocking authenticated paths, never touching internal hosts.',
                'sub_points' => [
                    'Cloudflare Browser Rendering for JS-heavy sites',
                    'Plain HTTP fallback for simple sites',
                    'Notion + Google Docs sources via OAuth',
                ],
            ],
            [
                'number' => '02',
                'title' => 'We index your knowledge',
                'duration' => '~30 seconds for most sites',
                'description' => 'Crawled pages are extracted (Readability), chunked along semantic boundaries (~500 tokens with overlap), embedded with Cloudflare bge-base-en-v1.5 or OpenAI text-embedding-3-small, and upserted into Vectorize or Qdrant — every chunk tagged with workspace + agent so retrieval is strictly tenant-scoped.',
                'sub_points' => [
                    'Recursive splitter — paragraphs first, sentences as fallback',
                    'Two-stage retrieval: ANN recall + cross-encoder rerank',
                    'Strict workspace isolation enforced by global query scope',
                ],
            ],
            [
                'number' => '03',
                'title' => 'Customize the agent',
                'duration' => '5 minutes of fine-tuning',
                'description' => "Set persona, tone, language, theme colors, starter prompts, and behavior rules. Add curated answers for pricing or refunds where you can't tolerate paraphrasing. A live preview shows visitors exactly what they'll see.",
                'sub_points' => [
                    '8 widget languages (en, es, fr, de, pt, ja, ar, zh)',
                    'Behavior rules: scroll-depth, idle, exit-intent, intent-keyword',
                    'A/B test rule variants and watch conversion deltas',
                ],
            ],
            [
                'number' => '04',
                'title' => 'Publish a snapshot',
                'duration' => 'instant',
                'description' => 'Hit Publish — we snapshot the agent into an immutable version row. The widget runtime always reads from the published version, so editing draft settings never affects live visitors. Roll back to any prior version with one click.',
                'sub_points' => [
                    'Versioned per-publish history',
                    'Strict allowed-origin enforcement on /v1/widget/init',
                    'One-click rollback to any prior snapshot',
                ],
            ],
            [
                'number' => '05',
                'title' => 'Embed one script tag',
                'duration' => '30 seconds',
                'description' => 'Paste a single &lt;script&gt; tag before &lt;/body&gt;. The widget bundle is &le; 50KB gzipped, async, and renders inside a Shadow DOM so it can\'t conflict with your site\'s CSS. Works on any framework — WordPress, Shopify, Next.js, plain HTML.',
                'sub_points' => [
                    'Shadow DOM isolation — no CSS leaks',
                    'Persistent visitor sessions across reloads',
                    'Optional voice mic (browser SpeechRecognition)',
                ],
            ],
            [
                'number' => '06',
                'title' => 'Visitor asks, AI answers',
                'duration' => '< 1 second to first token',
                'description' => 'A visitor types a question. Hot path: curated short-circuit check → embed query → vector search → rerank → assemble prompt with sources tagged for prompt-injection defense → stream LLM response back over SSE. No DB writes, no synchronous webhooks — persistence is async after the stream completes.',
                'sub_points' => [
                    'Hot-path 1s p95 TTFT contract enforced',
                    'Citations [1] [2] linking back to your sources',
                    'Confidence threshold per agent — agent says "I don\'t know" before guessing',
                ],
            ],
            [
                'number' => '07',
                'title' => 'Capture leads, jump in live',
                'duration' => 'when intent is high',
                'description' => 'Behavior rules detect when a visitor shows real intent (asks about pricing, asks for a demo, hits the third turn) and offer the inline lead form. Captured leads land in your inbox immediately, fire a Slack alert, and POST to your webhook for HubSpot / Pipedrive / Mailchimp.',
                'sub_points' => [
                    'Real-time inbox via Reverb WebSocket',
                    'One-click human takeover — visitor sees "Human is here"',
                    'Outgoing webhooks with HMAC-signed payloads',
                ],
            ],
        ];
    }

    /**
     * @return list<array{phase: string, budget: string}>
     */
    private function latencyBudget(): array
    {
        return [
            ['phase' => 'Receive + auth', 'budget' => '30 ms'],
            ['phase' => 'Curated short-circuit', 'budget' => '5 ms'],
            ['phase' => 'Embed query', 'budget' => '120 ms'],
            ['phase' => 'Vector search', 'budget' => '80 ms'],
            ['phase' => 'Rerank', 'budget' => '120 ms'],
            ['phase' => 'Prompt assembly', 'budget' => '10 ms'],
            ['phase' => 'LLM time-to-first-token', 'budget' => '500 ms'],
        ];
    }

    /**
     * @return list<array<string, mixed>>
     */
    private function nativeIntegrations(): array
    {
        return [
            [
                'name' => 'Notion',
                'category' => 'Knowledge source',
                'tagline' => 'Pipe your team\'s shared brain into the agent.',
                'description' => 'OAuth into your workspace, pick the pages or databases you want indexed, and changes you make in Notion show up in the agent\'s answers next time you reindex.',
                'icon' => 'BookOpen',
                'accent' => 'slate',
            ],
            [
                'name' => 'Google Docs',
                'category' => 'Knowledge source',
                'tagline' => 'Sync product specs and FAQs the moment they ship.',
                'description' => 'Connect via OAuth and pick the docs that matter. Each document becomes a knowledge source — manual reindex on change, no scheduled polling against your Drive.',
                'icon' => 'FileText',
                'accent' => 'sky',
            ],
            [
                'name' => 'Slack',
                'category' => 'Notifications',
                'tagline' => 'Pipe leads + escalations to the channel that handles them.',
                'description' => 'Pick a channel; new captured leads, low-confidence escalations, and routed conversations land in real time so a human can jump in from where they already work.',
                'icon' => 'MessageSquare',
                'accent' => 'violet',
            ],
            [
                'name' => 'Stripe',
                'category' => 'Billing',
                'tagline' => 'Self-serve checkout and recurring billing.',
                'description' => 'Subscriptions, plan changes, and invoices flow through Stripe Checkout + the Customer Portal. Plans defined in the admin auto-sync to Stripe Products and Prices.',
                'icon' => 'CreditCard',
                'accent' => 'indigo',
            ],
        ];
    }

    /**
     * @return list<array<string, mixed>>
     */
    private function dataSourceIntegrations(): array
    {
        return [
            ['name' => 'URL crawl', 'tagline' => 'Drop a URL, we pull the content respecting robots.txt.', 'icon' => 'Globe2'],
            ['name' => 'Sitemap', 'tagline' => 'Point at /sitemap.xml — we fan out to one job per page.', 'icon' => 'Map'],
            ['name' => 'RSS / Atom feeds', 'tagline' => 'Keep blog content fresh with feed-driven re-ingestion.', 'icon' => 'Rss'],
            ['name' => 'Pasted text', 'tagline' => 'Paste FAQs, scripts, or anything text-shaped — instant indexing.', 'icon' => 'Type'],
            ['name' => 'Auto-index visited pages', 'tagline' => 'Every page a visitor lands on gets indexed automatically (with guardrails).', 'icon' => 'Sparkles'],
        ];
    }

    /**
     * @return list<array<string, mixed>>
     */
    private function roadmapIntegrations(): array
    {
        return [
            ['name' => 'HubSpot', 'tagline' => 'Push leads as contacts and create deals on the configured pipeline.'],
            ['name' => 'Salesforce', 'tagline' => 'Native sync for Lead + Opportunity objects.'],
            ['name' => 'Pipedrive', 'tagline' => 'New deals + activities on lead capture.'],
            ['name' => 'Mailchimp', 'tagline' => 'Push leads as audience subscribers with conversation transcripts as custom fields.'],
            ['name' => 'Zapier', 'tagline' => 'Built-in trigger + action for the Zapier directory.'],
            ['name' => 'Calendly / Cal.com', 'tagline' => 'CTA buttons that open an inline booking widget mid-conversation.'],
        ];
    }

    private function termsIntro(): string
    {
        $brand = $this->brand();

        return "These terms govern your use of {$brand} (the “Service”). By creating an account, embedding the widget, or otherwise using the Service, you agree to these terms. If you do not agree, do not use the Service.";
    }

    /**
     * @return list<array{title: string, body?: array<int, string>, bullets?: array<int, string>}>
     */
    private function termsSections(): array
    {
        $brand = $this->brand();

        return [
            [
                'title' => '1. The Service',
                'body' => [
                    "{$brand} is an AI-powered website chat widget and operator console. We provide hosting for your agents, knowledge ingestion, retrieval, large-language-model responses, lead capture, and an inbox where your team can take over conversations from the AI. Specific capabilities, quotas, and limits are described on the pricing page and in your active subscription.",
                ],
            ],
            [
                'title' => '2. Your account',
                'bullets' => [
                    'You must provide accurate registration information and keep it current.',
                    'You are responsible for safeguarding your password and any access tokens.',
                    'You are responsible for all activity under your account, including activity by workspace members you invite.',
                    'You must promptly notify us of any unauthorized access or suspected breach.',
                    'You must be at least 16 years of age (or the age of digital consent in your jurisdiction).',
                ],
            ],
            [
                'title' => '3. Acceptable use',
                'body' => ['You agree not to use the Service to:'],
                'bullets' => [
                    'Violate any applicable law, regulation, or third-party right.',
                    'Send spam, harass, defraud, or impersonate any person or entity.',
                    'Distribute malware, conduct phishing, or attempt to compromise security.',
                    'Embed the widget on sites operated by third parties without their permission.',
                    'Reverse engineer, scrape, or attempt to derive source code beyond what is expressly permitted.',
                    'Resell, sublicense, or otherwise commercialize the Service except as expressly authorized.',
                    'Submit knowledge sources or visitor inputs that infringe copyright, contain unlawful content, or expose the personal data of individuals without a lawful basis.',
                ],
            ],
            [
                'title' => '4. Your content & data',
                'body' => [
                    'You retain ownership of the data you submit to the Service: knowledge sources, agent configuration, conversation transcripts, leads, and associated metadata (“Customer Data”). You grant us a worldwide, non-exclusive, royalty-free license to process Customer Data solely as needed to operate, secure, support, and improve the Service for you.',
                    'You represent that you have all rights necessary to submit Customer Data and that doing so does not violate any law or third-party right.',
                ],
            ],
            [
                'title' => '5. Visitor data & privacy',
                'body' => ['When you embed the widget on your site, visitor messages, IP-derived signals, and any contact details they submit pass through the Service. You are the controller of that data; we are the processor. You must:'],
                'bullets' => [
                    "Maintain a privacy notice that discloses the use of {$brand} and AI processing on your site.",
                    'Obtain any consents required by applicable law (GDPR, CCPA, equivalent).',
                    'Honor data subject rights for visitors who request access, correction, or deletion.',
                ],
            ],
            [
                'title' => '6. AI output disclaimer',
                'body' => ['AI responses are generated based on the knowledge sources you supply and the underlying language model. They may contain inaccuracies, omissions, or unintended outputs. You are responsible for:'],
                'bullets' => [
                    'Reviewing your knowledge base, system prompt, and behavior rules.',
                    'Configuring an appropriate confidence threshold for your use case.',
                    'Reviewing transcripts and capturing leads for any business-critical interaction.',
                ],
            ],
            [
                'title' => '7. Subscriptions, billing, & refunds',
                'bullets' => [
                    'Paid plans renew automatically until cancelled. You may cancel from your billing settings; cancellation takes effect at the end of the current billing period.',
                    'Fees are billed in advance and are non-refundable except where required by law or where we explicitly grant a refund.',
                    'You authorize us and our payment processor (Stripe) to charge the payment method on file.',
                    'If your usage exceeds your plan limits, we may rate-limit, block new conversations, or invite you to upgrade.',
                    'We may change pricing for new billing periods with reasonable notice.',
                ],
            ],
            [
                'title' => '8. Third-party services',
                'body' => [
                    'The Service integrates with third-party providers (large-language-model APIs, vector stores, payment processors, OAuth-based knowledge sources such as Notion or Google Drive, and your configured outgoing webhooks). Their availability, latency, and pricing are outside our control, and your use of those services is subject to their own terms.',
                ],
            ],
            [
                'title' => '9. Service availability',
                'body' => [
                    'We aim for high availability but do not guarantee uninterrupted access. We may perform maintenance, updates, or emergency response that briefly affects the Service. We are not liable for downtime caused by third-party providers or by force majeure.',
                ],
            ],
            [
                'title' => '10. Termination',
                'bullets' => [
                    'You may terminate by cancelling your subscription and deleting your workspace.',
                    'We may suspend or terminate the Service for violation of these terms, non-payment, or to comply with applicable law.',
                    'Upon termination we will retain Customer Data for a reasonable transition period (typically 30 days) before deletion.',
                ],
            ],
            [
                'title' => '11. Intellectual property',
                'body' => [
                    "The Service, including software, design, and trademarks, is owned by {$brand} and its licensors. Nothing in these terms grants you ownership of the Service. Feedback you provide may be used by us without obligation.",
                ],
            ],
            [
                'title' => '12. Disclaimers',
                'body' => [
                    'THE SERVICE IS PROVIDED “AS IS” WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. WE DO NOT WARRANT THAT THE SERVICE WILL BE ERROR-FREE OR UNINTERRUPTED, OR THAT AI OUTPUTS WILL BE ACCURATE.',
                ],
            ],
            [
                'title' => '13. Limitation of liability',
                'body' => [
                    'TO THE MAXIMUM EXTENT PERMITTED BY LAW, NEITHER PARTY WILL BE LIABLE FOR INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL, OR PUNITIVE DAMAGES, OR FOR LOST PROFITS, REVENUE, GOODWILL, OR DATA, ARISING OUT OF OR RELATED TO THE SERVICE. OUR AGGREGATE LIABILITY FOR ANY CLAIM WILL NOT EXCEED THE FEES YOU PAID FOR THE SERVICE IN THE 12 MONTHS PRECEDING THE CLAIM.',
                ],
            ],
            [
                'title' => '14. Indemnification',
                'body' => [
                    "You agree to defend and indemnify {$brand} against claims arising from (a) your Customer Data, (b) your use of the Service in violation of these terms, or (c) your violation of any law or third-party right.",
                ],
            ],
            [
                'title' => '15. Changes to these terms',
                'body' => [
                    'We may update these terms from time to time. Material changes will be announced via the Service or by email at least 14 days before they take effect. Continued use after the effective date constitutes acceptance.',
                ],
            ],
            [
                'title' => '16. Governing law',
                'body' => [
                    "These terms are governed by the laws of the jurisdiction in which the operator of {$brand} is established, without regard to conflict-of-law principles. Disputes will be resolved in the courts of that jurisdiction unless required otherwise by law.",
                ],
            ],
        ];
    }
}
