import { createServerClient } from '@/lib/supabase/server'
import { getPublicLanding, LandingContent } from '@/lib/api/platform'
import Link from 'next/link'
import {
  Activity,
  ArrowRight,
  BellRing,
  BrainCircuit,
  CheckCircle2,
  ClipboardList,
  FileSearch,
  Gauge,
  Handshake,
  PackageSearch,
  ShieldCheck,
  ShoppingCart,
  Truck,
  Users,
} from 'lucide-react'

async function isAuthenticated(): Promise<boolean> {
  try {
    const supabase = await createServerClient()
    const { data } = await supabase.auth.getUser()
    return Boolean(data.user)
  } catch {
    return false
  }
}

const CAPABILITIES = [
  'Manage orders end to end',
  'Detect inventory shortages automatically',
  'Find and compare suppliers by cost, speed and reliability',
  'Request human approval before spending money',
  'Automate approved procurement workflows',
  'Track fulfillment and delivery status',
  'Maintain a complete operational audit trail',
]

const STEPS = [
  {
    title: 'Order received',
    body: 'A customer order enters the system and an autonomous task is created for it.',
  },
  {
    title: 'Inventory analysis',
    body: 'IMBARAGA checks stock levels — including reserved quantities — to see if the order can be fulfilled from hand.',
  },
  {
    title: 'Shortage detection',
    body: 'When availability falls short, the agent flags exactly what is missing.',
  },
  {
    title: 'Supplier comparison',
    body: 'The agent ranks supplier offers on unit cost, delivery time, stock on hand and reliability score.',
  },
  {
    title: 'Human approval',
    body: 'A purchase recommendation is presented for review. Nothing is bought without a decision.',
  },
  {
    title: 'Procurement & fulfillment',
    body: 'Approved purchases are submitted, fulfilled atomically into inventory, then delivered — closing the loop.',
  },
]

const FEATURES = [
  {
    icon: Activity,
    title: 'Live agent timeline',
    body: 'Watch every step the agent takes in real time, with polling fallback so nothing is missed.',
  },
  {
    icon: Handshake,
    title: 'Approval center',
    body: 'Review recommendations with full context — costs, suppliers, trade-offs — and approve or reject in one click.',
  },
  {
    icon: ShoppingCart,
    title: 'Purchase requests',
    body: 'Every proposed purchase is recorded with deterministic totals computed by the database itself.',
  },
  {
    icon: PackageSearch,
    title: 'Inventory alerts',
    body: 'Low-stock and out-of-stock conditions raise notifications once per occurrence — never spam.',
  },
  {
    icon: BellRing,
    title: 'Notification center',
    body: 'Operational alerts and customer updates surface in one inbox inside the dashboard.',
  },
  {
    icon: Gauge,
    title: 'Operations analytics',
    body: 'Revenue, procurement spend, average agent run time and success rate at a glance.',
  },
  {
    icon: FileSearch,
    title: 'Complete audit log',
    body: 'Every action is traceable to its task, execution and order — searchable and filterable.',
  },
  {
    icon: Users,
    title: 'Customer records',
    body: 'Orders stay linked to customers, with notifications written at every lifecycle step.',
  },
]

export default async function LandingPage() {
  const authed = await isAuthenticated()
  const startHref = authed ? '/dashboard' : '/login'
  const landing: LandingContent = (await getPublicLanding()) as LandingContent
  const content: Record<string, string> = {}
  for (const key of [
    'badge',
    'title',
    'subtitle',
    'cta_primary',
    'cta_secondary',
    'demo_hint',
    'footer_note',
  ] as const) {
    const value = landing[key]
    if (typeof value === 'string' && value.trim()) content[key] = value.trim()
  }
  const ctaPrimary = content.cta_primary ?? 'Start Managing Operations'
  const ctaSecondary = content.cta_secondary ?? 'See How It Works'

  return (
    <div className="min-h-screen bg-white text-gray-900 dark:bg-gray-950 dark:text-gray-100">
      {/* Nav */}
      <header className="sticky top-0 z-30 border-b border-gray-200 bg-white/80 backdrop-blur-sm dark:border-gray-800 dark:bg-gray-950/80">
        <div className="mx-auto flex h-16 max-w-6xl items-center justify-between px-4 lg:px-6">
          <div className="flex items-center gap-2">
            <Activity className="h-7 w-7 text-indigo-600 dark:text-indigo-400" />
            <span className="text-lg font-bold">IMBARAGA</span>
          </div>
          <nav aria-label="Main" className="hidden md:flex items-center gap-6 text-sm font-medium text-gray-600 dark:text-gray-300">
            <a href="#problem" className="hover:text-indigo-600 dark:hover:text-indigo-400">Problem</a>
            <a href="#how-it-works" className="hover:text-indigo-600 dark:hover:text-indigo-400">How it works</a>
            <a href="#features" className="hover:text-indigo-600 dark:hover:text-indigo-400">Features</a>
            <a href="#security" className="hover:text-indigo-600 dark:hover:text-indigo-400">Security</a>
          </nav>
          <Link
            href={startHref}
            className="rounded-lg bg-indigo-600 px-4 py-2 text-sm font-semibold text-white transition-colors hover:bg-indigo-700"
          >
            Open Dashboard
          </Link>
        </div>
      </header>

      {/* 1. Hero */}
      <section className="relative overflow-hidden bg-gradient-to-b from-indigo-50 to-white dark:from-indigo-950/40 dark:to-gray-950">
        <div className="mx-auto max-w-6xl px-4 py-20 lg:px-6 lg:py-28">
          <div className="mx-auto max-w-3xl text-center">
            <p className="mb-4 inline-flex items-center gap-2 rounded-full bg-indigo-100 px-3 py-1 text-xs font-semibold uppercase tracking-wide text-indigo-700 dark:bg-indigo-900/40 dark:text-indigo-300">
              <BrainCircuit className="h-3.5 w-3.5" />
              {content.badge || 'Autonomous business operations'}
            </p>
            <h1 className="text-4xl font-extrabold leading-tight tracking-tight sm:text-5xl lg:text-6xl">
              {content.title || 'AI-Powered Operations for Growing Businesses'}
            </h1>
            <p className="mt-6 text-lg text-gray-600 dark:text-gray-300 sm:text-xl">
              {content.subtitle ||
                'IMBARAGA is an operations agent that turns customer orders into completed fulfillments — it checks inventory, finds and compares suppliers, and asks you only when a decision truly needs you.'}
            </p>
            <div className="mt-10 flex flex-col items-center justify-center gap-4 sm:flex-row">
              <Link
                href={startHref}
                className="inline-flex w-full items-center justify-center gap-2 rounded-xl bg-indigo-600 px-8 py-4 text-base font-semibold text-white shadow-sm transition-transform hover:-translate-y-0.5 hover:bg-indigo-700 sm:w-auto"
              >
                {ctaPrimary}
                <ArrowRight className="h-5 w-5" />
              </Link>
              <a
                href="#how-it-works"
                className="inline-flex w-full items-center justify-center gap-2 rounded-xl border border-gray-300 bg-white px-8 py-4 text-base font-semibold text-gray-700 transition-colors hover:bg-gray-50 sm:w-auto dark:border-gray-700 dark:bg-gray-900 dark:text-gray-200 dark:hover:bg-gray-800"
              >
                {ctaSecondary}
              </a>
            </div>
            {!authed && (
              <p className="mt-4 text-sm text-gray-500 dark:text-gray-400">
                {content.demo_hint || 'Demo login: demo@imbaraga.rw · password in README'}
              </p>
            )}
          </div>
        </div>
      </section>

      {/* 2. Problem */}
      <section id="problem" className="border-t border-gray-100 py-20 dark:border-gray-900">
        <div className="mx-auto max-w-6xl px-4 lg:px-6">
          <div className="grid items-center gap-12 lg:grid-cols-2">
            <div>
              <h2 className="text-3xl font-bold sm:text-4xl">Software exists. Coordination doesn&apos;t.</h2>
              <p className="mt-4 text-gray-600 dark:text-gray-300">
                A customer order sets off a chain reaction: check stock, discover shortages, contact suppliers,
                compare offers, decide, purchase, update records, inform the customer, follow through.
                Each tool handles one step — the owner is still the integration layer.
              </p>
            </div>
            <ul className="space-y-3">
              {[
                'Stock checks done by eye, shortages found too late',
                'Supplier quotes compared in spreadsheets and chat threads',
                'Purchases delayed waiting on one busy decision-maker',
                'Records updated hours after reality — if at all',
                'No traceable history of who did what, and when',
              ].map(item => (
                <li key={item} className="flex items-start gap-3 rounded-xl border border-red-100 bg-red-50/60 p-4 text-sm dark:border-red-900/30 dark:bg-red-950/20">
                  <span aria-hidden className="mt-0.5 h-2 w-2 shrink-0 rounded-full bg-red-500" />
                  <span className="text-gray-700 dark:text-gray-200">{item}</span>
                </li>
              ))}
            </ul>
          </div>
        </div>
      </section>

      {/* 3. Solution */}
      <section className="bg-gray-50 py-20 dark:bg-gray-900/50">
        <div className="mx-auto max-w-6xl px-4 lg:px-6">
          <h2 className="text-center text-3xl font-bold sm:text-4xl">An operations employee that works in the background</h2>
          <p className="mx-auto mt-4 max-w-2xl text-center text-gray-600 dark:text-gray-300">
            Give IMBARAGA a business objective — like a new order — and it plans the steps, uses your business tools,
            executes the workflow, and escalates only when judgment is required.
          </p>
          <ul className="mx-auto mt-10 grid max-w-3xl gap-3 sm:grid-cols-2">
            {CAPABILITIES.map(cap => (
              <li key={cap} className="flex items-start gap-3 rounded-xl border border-gray-200 bg-white p-4 text-sm shadow-sm dark:border-gray-800 dark:bg-gray-950">
                <CheckCircle2 className="mt-0.5 h-5 w-5 shrink-0 text-emerald-500" />
                <span>{cap}</span>
              </li>
            ))}
          </ul>
        </div>
      </section>

      {/* 4. How it works */}
      <section id="how-it-works" className="py-20">
        <div className="mx-auto max-w-6xl px-4 lg:px-6">
          <h2 className="text-center text-3xl font-bold sm:text-4xl">How IMBARAGA works</h2>
          <ol className="mt-12 space-y-4">
            {STEPS.map((step, i) => (
              <li key={step.title} className="flex gap-4 rounded-2xl border border-gray-200 p-6 transition-shadow hover:shadow-md dark:border-gray-800">
                <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-indigo-600 text-sm font-bold text-white">
                  {i + 1}
                </span>
                <div>
                  <h3 className="font-semibold">{step.title}</h3>
                  <p className="mt-1 text-sm text-gray-600 dark:text-gray-300">{step.body}</p>
                </div>
              </li>
            ))}
          </ol>
        </div>
      </section>

      {/* 5. AI + human approval architecture */}
      <section className="bg-gradient-to-b from-indigo-50 to-white py-20 dark:from-indigo-950/30 dark:to-gray-950">
        <div className="mx-auto max-w-6xl px-4 lg:px-6">
          <h2 className="text-center text-3xl font-bold sm:text-4xl">Deterministic where it matters.<br className="hidden sm:block" /> Human where it counts.</h2>
          <div className="mt-12 grid gap-6 lg:grid-cols-3">
            <div className="rounded-2xl border border-gray-200 bg-white p-6 dark:border-gray-800 dark:bg-gray-950">
              <ClipboardList className="h-8 w-8 text-indigo-600 dark:text-indigo-400" />
              <h3 className="mt-4 font-semibold">Rules run the workflow</h3>
              <p className="mt-2 text-sm text-gray-600 dark:text-gray-300">
                Prices, quantities, thresholds, inventory changes and state transitions are executed by
                deterministic code and database functions — auditable and repeatable.
              </p>
            </div>
            <div className="rounded-2xl border border-gray-200 bg-white p-6 dark:border-gray-800 dark:bg-gray-950">
              <BrainCircuit className="h-8 w-8 text-indigo-600 dark:text-indigo-400" />
              <h3 className="mt-4 font-semibold">AI advises, never decides</h3>
              <p className="mt-2 text-sm text-gray-600 dark:text-gray-300">
                The Gemini-powered supervisor adds plain-language analysis of each situation.
                It is explicitly advisory: its output cannot mutate data or bypass controls.
              </p>
            </div>
            <div className="rounded-2xl border border-gray-200 bg-white p-6 dark:border-gray-800 dark:bg-gray-950">
              <Handshake className="h-8 w-8 text-indigo-600 dark:text-indigo-400" />
              <h3 className="mt-4 font-semibold">You approve the spend</h3>
              <p className="mt-2 text-sm text-gray-600 dark:text-gray-300">
                Every purchase request waits for a human decision. Approve, reject or let it expire —
                the agent proceeds only after you do.
              </p>
            </div>
          </div>
        </div>
      </section>

      {/* 6. Features */}
      <section id="features" className="py-20">
        <div className="mx-auto max-w-6xl px-4 lg:px-6">
          <h2 className="text-center text-3xl font-bold sm:text-4xl">Everything an operator needs, in one place</h2>
          <div className="mt-12 grid gap-6 sm:grid-cols-2 lg:grid-cols-4">
            {FEATURES.map(f => (
              <div key={f.title} className="rounded-2xl border border-gray-200 p-6 transition-transform hover:-translate-y-0.5 dark:border-gray-800">
                <f.icon className="h-7 w-7 text-indigo-600 dark:text-indigo-400" aria-hidden />
                <h3 className="mt-3 font-semibold">{f.title}</h3>
                <p className="mt-2 text-sm text-gray-600 dark:text-gray-300">{f.body}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* 7. Workflow visualization */}
      <section className="bg-gray-50 py-20 dark:bg-gray-900/50">
        <div className="mx-auto max-w-4xl px-4 lg:px-6">
          <h2 className="text-center text-3xl font-bold sm:text-4xl">From order to delivery, autonomously</h2>
          <div className="mt-12 flex flex-col items-stretch gap-2">
            {[
              { label: 'New order received', icon: ClipboardList },
              { label: 'Agent analyzes inventory', icon: PackageSearch },
              { label: 'Shortage detected & suppliers compared', icon: Users },
              { label: 'Human approval requested', icon: Handshake },
              { label: 'Purchase fulfilled into inventory', icon: ShoppingCart },
              { label: 'Order ready & delivered', icon: Truck },
            ].map((step, i, arr) => (
              <div key={step.label}>
                <div className="flex items-center gap-4 rounded-xl border border-gray-200 bg-white p-4 shadow-sm dark:border-gray-800 dark:bg-gray-950">
                  <step.icon className="h-6 w-6 shrink-0 text-indigo-600 dark:text-indigo-400" aria-hidden />
                  <span className="text-sm font-medium sm:text-base">{step.label}</span>
                </div>
                {i < arr.length - 1 && (
                  <div aria-hidden className="ml-8 h-4 w-px bg-gray-300 dark:bg-gray-700" />
                )}
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* 8. Analytics */}
      <section className="py-20">
        <div className="mx-auto max-w-6xl px-4 lg:px-6">
          <div className="grid items-center gap-12 lg:grid-cols-2">
            <div>
              <h2 className="text-3xl font-bold sm:text-4xl">Insights built in, not bolted on</h2>
              <p className="mt-4 text-gray-600 dark:text-gray-300">
                Because the agent records every action, the dashboard can show what matters without extra setup:
                money coming in, money going out, how long autonomous runs take, and how often they succeed.
              </p>
            </div>
            <div className="grid grid-cols-2 gap-4">
              {[
                ['Completed revenue', 'from delivered orders'],
                ['Procurement spend', 'from fulfilled purchases'],
                ['Average agent run', 'execution duration'],
                ['Success rate', 'finished runs vs failures'],
              ].map(([title, sub]) => (
                <div key={title} className="rounded-2xl border border-gray-200 p-6 dark:border-gray-800">
                  <p className="text-sm text-gray-500 dark:text-gray-400">{sub}</p>
                  <p className="mt-1 font-semibold">{title}</p>
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>

      {/* 9. Security & auditability */}
      <section id="security" className="bg-gray-50 py-20 dark:bg-gray-900/50">
        <div className="mx-auto max-w-6xl px-4 lg:px-6">
          <h2 className="text-center text-3xl font-bold sm:text-4xl">Secure and auditable by design</h2>
          <div className="mt-12 grid gap-6 sm:grid-cols-2 lg:grid-cols-4">
            {[
              ['Row-level isolation', 'Every table enforces business ownership at the database level.'],
              ['Atomic stock control', 'Reservations and fulfillment run inside database transactions — no double-spending inventory.'],
              ['Idempotent workflows', 'Retried orders never create duplicate tasks or duplicate purchases.'],
              ['Full audit trail', 'Alerts, approvals, purchases and deliveries are all recorded with their actor and context.'],
            ].map(([title, body]) => (
              <div key={title} className="rounded-2xl border border-gray-200 bg-white p-6 dark:border-gray-800 dark:bg-gray-950">
                <ShieldCheck className="h-7 w-7 text-emerald-500" aria-hidden />
                <h3 className="mt-3 font-semibold">{title}</h3>
                <p className="mt-2 text-sm text-gray-600 dark:text-gray-300">{body}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* 10. CTA */}
      <section className="bg-indigo-600 py-20 text-white">
        <div className="mx-auto max-w-3xl px-4 text-center lg:px-6">
          <h2 className="text-3xl font-bold sm:text-4xl">Put your operations on autopilot</h2>
          <p className="mt-4 text-indigo-100">
            Try the live demo workspace: trigger an order, watch the agent work, and make the call when it asks.
          </p>
          <Link
            href={startHref}
            className="mt-8 inline-flex items-center gap-2 rounded-xl bg-white px-8 py-4 text-base font-semibold text-indigo-700 transition-transform hover:-translate-y-0.5"
          >
            {ctaPrimary}
            <ArrowRight className="h-5 w-5" />
          </Link>
        </div>
      </section>

      {/* 11. Footer */}
      <footer className="border-t border-gray-200 py-10 dark:border-gray-900">
        <div className="mx-auto flex max-w-6xl flex-col items-center justify-between gap-4 px-4 sm:flex-row lg:px-6">
          <div className="flex items-center gap-2">
            <Activity className="h-5 w-5 text-indigo-600 dark:text-indigo-400" />
            <span className="font-semibold">IMBARAGA</span>
          </div>
          <p className="text-sm text-gray-500 dark:text-gray-400">
            {content.footer_note || 'Built for the All Things Agentic Hackathon · © 2026'}
          </p>
          <Link href="/login" className="text-sm font-medium text-indigo-600 hover:underline dark:text-indigo-400">
            Sign in
          </Link>
        </div>
      </footer>
    </div>
  )
}
