import React, {
  FormEvent,
  ReactElement,
  useEffect,
  useMemo,
  useState,
} from 'react';
import Head from 'next/head';
import Link from 'next/link';
import BaseButton from '../components/BaseButton';
import CardBox from '../components/CardBox';
import LayoutGuest from '../layouts/Guest';
import { getPageTitle } from '../config';

type TrustForm = {
  profileName: string;
  profileType: 'creator' | 'umkm' | 'company';
  verifiedDocuments: string;
  hasBiometric: boolean;
  hasTaxId: boolean;
  hasTransactionHistory: boolean;
  citedSources: string;
  verifiedReviews: boolean;
  localPresence: boolean;
};

type TrustReport = TrustForm & {
  id: string;
  score: number;
  tier: string;
  createdAt: string;
  recommendations: string[];
};

type SectionLink = {
  id: string;
  label: string;
};

type WorkspaceModule = {
  title: string;
  description: string;
  metric: string;
  sectionId: string;
};

type Pillar = {
  title: string;
  description: string;
  route: string;
  actionLabel: string;
};

const defaultForm: TrustForm = {
  profileName: '',
  profileType: 'umkm',
  verifiedDocuments: '2',
  hasBiometric: true,
  hasTaxId: false,
  hasTransactionHistory: true,
  citedSources: '1',
  verifiedReviews: false,
  localPresence: true,
};

const storageKey = 'vorta-trust-reports';

const profileTypeLabels: Record<TrustForm['profileType'], string> = {
  creator: 'Kreator',
  umkm: 'UMKM',
  company: 'Perusahaan',
};

const sectionLinks: SectionLink[] = [
  { id: 'home', label: 'Beranda' },
  { id: 'workspace-preview', label: 'Workspace' },
  { id: 'pillars', label: 'VORTA Universe' },
  { id: 'trust-flow', label: 'Skor' },
  { id: 'reports', label: 'Laporan' },
];

const workspaceModules: WorkspaceModule[] = [
  {
    title: 'Chat bisnis',
    description: 'Buka alur percakapan tim, pembeli, dan penjual.',
    metric: '42 pesan',
    sectionId: 'pillars',
  },
  {
    title: 'Feed sosial',
    description: 'Lihat komunitas dan reputasi yang terhubung skor Nexus.',
    metric: '31 update',
    sectionId: 'trust-flow',
  },
  {
    title: 'Marketplace',
    description: 'Jalankan simulasi toko, produk, dan ulasan terverifikasi.',
    metric: '18 produk',
    sectionId: 'trust-flow',
  },
  {
    title: 'Dompet digital',
    description: 'Pantau dompet, transaksi, dan aktivitas pembayaran ringan.',
    metric: '37 transaksi',
    sectionId: 'reports',
  },
];

const pillars: Pillar[] = [
  {
    title: 'VORTA Commerce',
    description:
      'VORTA Commerce adalah platform utama dalam ekosistem VORTA Universe yang menghubungkan perdagangan, distribusi, komunitas, logistik, afiliasi, dan pembayaran berbasis kepercayaan.',
    route: '/vorta-commerce',
    actionLabel: 'Buka Commerce',
  },
  {
    title: 'Vorta Synapse',
    description:
      'Protokol Distribusi, Afiliasi, Dan Logistik Pintar Untuk Ekonomi Kreator.',
    route: '/vorta-synapse',
    actionLabel: 'Buka Synapse',
  },
  {
    title: 'Mega Super-App',
    description:
      'Chat Bisnis, Sosial, Marketplace, Dan Dompet Dalam Satu Ruang Kerja Ringan.',
    route: '/mega-super-app',
    actionLabel: 'Buka Super-App',
  },
  {
    title: 'Vorta Nexus',
    description:
      'Skor Kepercayaan 0-100 Untuk Identitas, Bisnis, Ulasan, Dan Akses Komunitas.',
    route: '/vorta-universe#vorta-overview',
    actionLabel: 'Buka Nexus',
  },
  {
    title: 'Facta.Ai',
    description:
      'Riset Bebas Seo Spam Dengan Truth Score Dan Peta Rujukan Langsung.',
    route: '/facta_queries/facta_queries-list',
    actionLabel: 'Buka Facta.Ai',
  },
];

const commerceVision =
  'Membangun ekosistem perdagangan digital berbasis kepercayaan terbesar yang menghubungkan seluruh rantai ekonomi dalam satu platform.';

const commerceMission = [
  'Membantu UMKM berkembang secara digital.',
  'Menghubungkan pembeli dan penjual secara aman.',
  'Mempercepat distribusi produk dan jasa.',
  'Mendukung ekonomi kreator dan afiliasi.',
  'Membangun komunitas bisnis yang aktif.',
  'Menyederhanakan komunikasi dan pembayaran.',
];

const commercePillars = [
  {
    title: 'Commerce',
    description: 'Pusat perdagangan digital.',
    features: [
      'Marketplace',
      'Toko Online',
      'Produk',
      'Keranjang Belanja',
      'Checkout',
      'Pesanan',
      'Pengiriman',
      'Retur',
      'Review',
    ],
  },
  {
    title: 'Distribution & Affiliate',
    description: 'Mesin pertumbuhan bisnis.',
    features: [
      'Affiliate Program',
      'Referral Program',
      'Komisi Otomatis',
      'Creator Partner',
      'Reseller Network',
      'Distributor Network',
      'Tracking Penjualan',
      'Dashboard Komisi',
    ],
  },
  {
    title: 'Smart Logistics',
    description: 'Sistem logistik terintegrasi.',
    features: [
      'Tracking Pengiriman',
      'Multi Kurir',
      'Pengiriman Lokal',
      'Pengiriman Nasional',
      'Estimasi Ongkir',
      'Smart Routing',
      'Manajemen Gudang',
    ],
  },
  {
    title: 'Social Commerce',
    description: 'Komunitas dan promosi dalam satu tempat.',
    features: ['Feed Sosial', 'Like', 'Komentar'],
  },
];

const getTier = (score: number) => {
  if (score >= 86) return 'Nexus Prime';
  if (score >= 70) return 'Pertumbuhan Terverifikasi';
  if (score >= 31) return 'Layak Pulse';

  return 'Perlu Verifikasi';
};

const clampNumber = (value: string, min: number, max: number) => {
  const parsed = Number.parseInt(value, 10);

  if (Number.isNaN(parsed)) return min;

  return Math.min(Math.max(parsed, min), max);
};

const buildRecommendations = (form: TrustForm, score: number) => {
  const recommendations = [];
  const documents = clampNumber(form.verifiedDocuments, 0, 4);
  const sources = clampNumber(form.citedSources, 0, 5);

  if (!form.hasBiometric)
    recommendations.push(
      'Aktifkan pencocokan wajah untuk mengikat akun dengan manusia asli.',
    );
  if (!form.hasTaxId)
    recommendations.push(
      'Tambahkan NPWP atau legalitas bisnis untuk transaksi bernilai tinggi.',
    );
  if (documents < 3)
    recommendations.push(
      'Unggah minimal tiga dokumen valid agar skor Nexus naik lebih cepat.',
    );
  if (sources < 3)
    recommendations.push(
      'Tambahkan Deep Dive Link primer agar konten lolos cek sitasi Facta.',
    );
  if (!form.verifiedReviews)
    recommendations.push(
      'Kunci ulasan hanya dari pembeli terverifikasi untuk ulasan bebas manipulasi.',
    );
  if (score < 31)
    recommendations.push(
      'Prioritaskan verifikasi dasar agar dapat menulis di Vorta Pulse.',
    );

  return recommendations.length
    ? recommendations
    : ['Profil siap diprioritaskan untuk visibilitas organik lintas VORTA.'];
};

const calculateReport = (form: TrustForm): TrustReport => {
  const documents = clampNumber(form.verifiedDocuments, 0, 4);
  const sources = clampNumber(form.citedSources, 0, 5);
  const score = Math.min(
    100,
    14 +
      documents * 9 +
      (form.hasBiometric ? 18 : 0) +
      (form.hasTaxId ? 12 : 0) +
      (form.hasTransactionHistory ? 14 : 0) +
      sources * 4 +
      (form.verifiedReviews ? 10 : 0) +
      (form.localPresence ? 6 : 0),
  );

  return {
    ...form,
    verifiedDocuments: String(documents),
    citedSources: String(sources),
    id: `${Date.now()}`,
    score,
    tier: getTier(score),
    createdAt: new Date().toISOString(),
    recommendations: buildRecommendations(form, score),
  };
};

const scoreGradient = (score: number) => {
  if (score >= 70) return 'from-emerald-400 to-cyan-300';
  if (score >= 31) return 'from-amber-300 to-orange-400';

  return 'from-rose-400 to-red-500';
};

const scrollToSection = (sectionId: string) => {
  const element = document.getElementById(sectionId);

  if (element) {
    element.scrollIntoView({ behavior: 'smooth', block: 'start' });
  }
};

export default function VortaLanding() {
  const [form, setForm] = useState<TrustForm>(defaultForm);
  const [reports, setReports] = useState<TrustReport[]>([]);
  const [activeReportId, setActiveReportId] = useState<string>('');
  const [errorMessage, setErrorMessage] = useState('');
  const [activeWorkspaceModule, setActiveWorkspaceModule] = useState(
    workspaceModules[0].title,
  );
  const [frontActionMessage, setFrontActionMessage] = useState(
    'Semua menu dan tombol muka siap dijalankan.',
  );
  const [activePillarTitle, setActivePillarTitle] = useState(pillars[0].title);

  useEffect(() => {
    try {
      const stored = window.localStorage.getItem(storageKey);
      const parsedReports = stored ? (JSON.parse(stored) as TrustReport[]) : [];

      if (Array.isArray(parsedReports)) {
        const normalizedReports = parsedReports.map((report) => ({
          ...report,
          tier: getTier(report.score),
          recommendations: buildRecommendations(report, report.score),
        }));

        setReports(normalizedReports);
        setActiveReportId(normalizedReports[0]?.id || '');
      }
    } catch (error) {
      console.error(
        'Failed to read VORTA trust reports from localStorage:',
        error,
      );
      window.localStorage.removeItem(storageKey);
    }
  }, []);

  useEffect(() => {
    window.localStorage.setItem(storageKey, JSON.stringify(reports));
  }, [reports]);

  const activeReport = useMemo(
    () => reports.find((report) => report.id === activeReportId) || reports[0],
    [activeReportId, reports],
  );

  const updateField = (field: keyof TrustForm, value: string | boolean) => {
    setForm((current) => ({ ...current, [field]: value }));
  };

  const saveReport = (nextForm: TrustForm) => {
    const report = calculateReport(nextForm);

    setReports((current) => [report, ...current].slice(0, 6));
    setActiveReportId(report.id);
    window.setTimeout(() => scrollToSection('reports'), 100);
  };

  const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    const trimmedName = form.profileName.trim();

    if (trimmedName.length < 3) {
      setErrorMessage(
        'Nama profil minimal 3 karakter agar laporan dapat dibuat.',
      );
      return;
    }

    setErrorMessage('');
    setFrontActionMessage(
      `Laporan Kepercayaan untuk ${trimmedName} berhasil dibuat.`,
    );
    saveReport({ ...form, profileName: trimmedName });
  };

  const handleSampleReport = () => {
    const sampleForm: TrustForm = {
      profileName: 'Warung Nusantara Bandung',
      profileType: 'umkm',
      verifiedDocuments: '4',
      hasBiometric: true,
      hasTaxId: true,
      hasTransactionHistory: true,
      citedSources: '4',
      verifiedReviews: true,
      localPresence: true,
    };

    setForm(sampleForm);
    setErrorMessage('');
    setFrontActionMessage('Contoh cepat dibuat dan detail laporan dibuka.');
    saveReport(sampleForm);
  };

  const handleResetForm = () => {
    setForm(defaultForm);
    setErrorMessage('');
    setFrontActionMessage('Formulir simulator dikembalikan ke nilai awal.');
    scrollToSection('trust-flow');
  };

  const handleSectionNavigation = (sectionId: string, label: string) => {
    setFrontActionMessage(`Menu ${label} dibuka.`);
    scrollToSection(sectionId);
  };

  const handleWorkspaceModule = (module: WorkspaceModule) => {
    setActiveWorkspaceModule(module.title);
    setFrontActionMessage(`${module.title} aktif: ${module.description}`);
    scrollToSection(module.sectionId);
  };

  const handlePillarPreview = (pillar: Pillar) => {
    setActivePillarTitle(pillar.title);
    setFrontActionMessage(
      `${pillar.title} dipilih. Tekan "${pillar.actionLabel}" untuk membuka halaman modul.`,
    );
    scrollToSection('pillars');
  };

  const handleStartDemo = () => {
    setForm({
      ...defaultForm,
      profileName: 'Demo VORTA Universe',
      verifiedDocuments: '3',
      citedSources: '3',
      hasTaxId: true,
      verifiedReviews: true,
    });
    setErrorMessage('');
    setFrontActionMessage(
      'Demo skor siap. Periksa formulir lalu tekan Buat Laporan Kepercayaan.',
    );
    scrollToSection('trust-flow');
  };

  const handleClearReports = () => {
    setReports([]);
    setActiveReportId('');
    setFrontActionMessage(
      'Semua riwayat laporan demo di browser ini dibersihkan.',
    );
    scrollToSection('reports');
  };

  const stats = [
    { label: 'produk utama', value: '5 modul' },
    { label: 'ruang kerja', value: '1 app' },
    { label: 'akses ringan', value: '<3 detik' },
  ];

  return (
    <>
      <Head>
        <title>{getPageTitle('VORTA Universe')}</title>
        <meta
          name='description'
          content='VORTA Universe mengurutkan VORTA Commerce, Vorta Synapse, Mega Super-App, Vorta Nexus, dan Facta.Ai sebagai ekosistem produk utama.'
        />
      </Head>

      <main
        id='home'
        className='min-h-screen overflow-hidden bg-[#07111f] text-white'
      >
        <section className='relative isolate px-5 py-5 sm:px-8 lg:px-12'>
          <div className='absolute inset-0 -z-10 bg-[radial-gradient(circle_at_top_left,#1de9b6_0,transparent_30%),radial-gradient(circle_at_80%_20%,#6c63ff_0,transparent_28%),linear-gradient(135deg,#07111f_0%,#101b34_45%,#07111f_100%)] opacity-95' />
          <div className='absolute left-1/2 top-20 -z-10 h-72 w-72 -translate-x-1/2 rounded-full bg-cyan-400/20 blur-3xl' />

          <nav className='mx-auto flex max-w-7xl items-center justify-between rounded-full border border-white/10 bg-white/[0.08] px-4 py-3 shadow-2xl shadow-cyan-950/30 backdrop-blur-xl'>
            <Link
              href='/'
              className='flex items-center gap-3 font-semibold tracking-wide'
            >
              <span className='grid h-10 w-10 place-items-center rounded-2xl bg-gradient-to-br from-[#1DE9B6] to-[#6C63FF] text-lg font-black text-[#07111f]'>
                V
              </span>
              <span>VORTA UNIVERSE</span>
            </Link>
            <div className='hidden items-center gap-2 text-sm text-slate-300 md:flex'>
              {sectionLinks.map((item) => (
                <button
                  key={item.id}
                  type='button'
                  onClick={() => handleSectionNavigation(item.id, item.label)}
                  className='rounded-full px-4 py-2 transition hover:bg-white/10 hover:text-white focus:outline-none focus:ring-2 focus:ring-cyan-300/50'
                >
                  {item.label}
                </button>
              ))}
            </div>
            <BaseButton
              href='/login'
              label='Masuk Admin'
              color='info'
              roundedFull
              className='border-cyan-300/40 bg-cyan-300 text-slate-950 hover:bg-white'
            />
          </nav>

          <div className='mx-auto mt-4 flex max-w-7xl flex-wrap justify-center gap-2 text-sm text-slate-200 md:hidden'>
            {sectionLinks.map((item) => (
              <button
                key={item.id}
                type='button'
                onClick={() => handleSectionNavigation(item.id, item.label)}
                className='rounded-full border border-white/10 bg-white/[0.08] px-4 py-2 transition hover:bg-white/15 focus:outline-none focus:ring-2 focus:ring-cyan-300/50'
              >
                {item.label}
              </button>
            ))}
          </div>

          <div className='mx-auto grid max-w-7xl gap-10 py-20 lg:grid-cols-[1.05fr_0.95fr] lg:items-center lg:py-28'>
            <div>
              <div className='mb-6 inline-flex rounded-full border border-emerald-300/30 bg-emerald-300/10 px-4 py-2 text-sm font-medium text-emerald-100'>
                VORTA UNIVERSE • 1. VORTA Commerce
              </div>
              <h1 className='max-w-4xl text-5xl font-black leading-tight tracking-tight text-white md:text-7xl'>
                Ekosistem perdagangan, distribusi, super-app, kepercayaan, dan riset berbasis kebenaran.
              </h1>
              <p className='mt-6 max-w-2xl text-lg leading-8 text-slate-300'>
                VORTA Commerce adalah platform utama dalam ekosistem VORTA Universe yang menghubungkan pembeli, penjual, UMKM, kreator, perusahaan, komunitas, afiliator, dan mitra logistik melalui sistem perdagangan berbasis kepercayaan (Trust-Based Commerce). VORTA Commerce tidak hanya berfungsi sebagai marketplace, tetapi juga sebagai pusat aktivitas bisnis digital yang menggabungkan perdagangan, distribusi, afiliasi, logistik, komunikasi, komunitas, dan pembayaran dalam satu platform terpadu. Dengan dukungan VORTA Nexus Trust Score, setiap identitas, toko, produk, ulasan, transaksi, dan aktivitas komunitas memiliki tingkat kepercayaan yang dapat diukur dan diverifikasi.
              </p>
              <div className='mt-9 flex flex-col gap-3 sm:flex-row'>
                <BaseButton
                  onClick={() =>
                    handleSectionNavigation('pillars', 'Alur Super-App')
                  }
                  label='Lihat Urutan VORTA Universe'
                  color='success'
                  roundedFull
                  className='border-emerald-300 bg-[#1DE9B6] px-7 py-3 text-slate-950 hover:bg-white'
                />
                <BaseButton
                  onClick={handleStartDemo}
                  label='Jalankan Demo Nexus'
                  color='white'
                  outline
                  roundedFull
                  className='border-white/30 bg-white/5 px-7 py-3 text-white hover:bg-white hover:text-slate-950'
                />
                <BaseButton
                  href='/login'
                  label='Masuk ke Admin'
                  color='white'
                  outline
                  roundedFull
                  className='border-white/30 bg-white/5 px-7 py-3 text-white hover:bg-white hover:text-slate-950'
                />
              </div>
              <div className='mt-5 rounded-3xl border border-white/10 bg-white/[0.08] px-5 py-4 text-sm font-semibold text-cyan-100'>
                Status: {frontActionMessage}
              </div>
              <div className='mt-10 grid max-w-xl grid-cols-3 gap-3'>
                {stats.map((stat) => (
                  <div
                    key={stat.label}
                    className='rounded-3xl border border-white/10 bg-white/[0.08] p-4 backdrop-blur'
                  >
                    <div className='text-2xl font-black text-[#1DE9B6]'>
                      {stat.value}
                    </div>
                    <div className='mt-1 text-xs uppercase tracking-[0.22em] text-slate-400'>
                      {stat.label}
                    </div>
                  </div>
                ))}
              </div>
            </div>

            <div id='workspace-preview' className='relative scroll-mt-24'>
              <div className='absolute -inset-4 rounded-[2rem] bg-gradient-to-br from-cyan-300/30 via-indigo-400/20 to-emerald-300/20 blur-2xl' />
              <CardBox
                className='relative border-white/10 bg-white/10 text-white shadow-2xl shadow-black/30 backdrop-blur-2xl'
                cardBoxClassName='p-0'
              >
                <div className='rounded-t-2xl border-b border-white/10 bg-slate-950/60 px-6 py-4'>
                  <div className='flex items-center justify-between'>
                    <div>
                      <p className='text-sm text-slate-400'>
                        Pratinjau ruang kerja langsung
                      </p>
                      <h2 className='text-xl font-bold'>
                        VORTA Universe Workspace
                      </h2>
                    </div>
                    <span className='rounded-full bg-emerald-300/15 px-3 py-1 text-xs font-semibold text-emerald-200'>
                      AKTIF
                    </span>
                  </div>
                </div>
                <div className='space-y-5 p-6'>
                  <div className='grid grid-cols-2 gap-3'>
                    {workspaceModules.map((module) => (
                      <button
                        key={module.title}
                        type='button'
                        onClick={() => handleWorkspaceModule(module)}
                        className={`rounded-2xl border p-4 text-left transition hover:-translate-y-0.5 hover:border-cyan-200/40 hover:bg-white/15 focus:outline-none focus:ring-4 focus:ring-cyan-300/30 ${
                          activeWorkspaceModule === module.title
                            ? 'border-cyan-200/60 bg-cyan-200/15'
                            : 'border-white/10 bg-white/[0.08]'
                        }`}
                      >
                        <div className='mb-3 h-2 w-12 rounded-full bg-gradient-to-r from-[#1DE9B6] to-[#6C63FF]' />
                        <p className='text-sm font-semibold'>{module.title}</p>
                        <p className='mt-2 text-xs leading-5 text-slate-300'>
                          {module.description}
                        </p>
                        <span className='mt-3 inline-flex rounded-full bg-white/10 px-3 py-1 text-[11px] font-bold uppercase tracking-[0.16em] text-cyan-100'>
                          {module.metric}
                        </span>
                      </button>
                    ))}
                  </div>
                  <div className='rounded-3xl border border-cyan-200/20 bg-cyan-200/10 p-5'>
                    <div className='flex items-end justify-between'>
                      <div>
                        <p className='text-sm text-cyan-100/80'>
                          Modul aktif: {activeWorkspaceModule}
                        </p>
                        <p className='text-5xl font-black text-cyan-100'>128</p>
                      </div>
                      <button
                        type='button'
                        onClick={() =>
                          handleSectionNavigation(
                            'trust-flow',
                            'Simulator Skor',
                          )
                        }
                        className='rounded-full bg-white px-3 py-1 text-sm font-bold text-slate-950 transition hover:bg-cyan-100 focus:outline-none focus:ring-4 focus:ring-cyan-300/30'
                      >
                        Jalankan sinkronisasi
                      </button>
                    </div>
                    <div className='mt-5 h-3 rounded-full bg-slate-900/70'>
                      <div className='h-3 w-[92%] rounded-full bg-gradient-to-r from-[#1DE9B6] to-[#6C63FF]' />
                    </div>
                  </div>
                </div>
              </CardBox>
            </div>
          </div>
        </section>

        <section
          id='pillars'
          className='border-y border-white/10 bg-white/[0.03] px-5 py-16 sm:px-8 lg:px-12'
        >
          <div className='mx-auto max-w-7xl'>
            <div className='mb-8 max-w-2xl'>
              <p className='text-sm font-semibold tracking-[0.28em] text-[#1DE9B6]'>
                VORTA UNIVERSE • 1. VORTA Commerce
              </p>
              <h2 className='mt-3 text-3xl font-black md:text-4xl'>
                Semua produk, menu, dan tombol utama mengikuti urutan 1 sampai 5 berikut.
              </h2>
              <p className='mt-4 rounded-3xl border border-white/10 bg-white/[0.08] px-5 py-3 text-sm font-semibold text-cyan-100'>
                Pilar aktif: {activePillarTitle}
              </p>
            </div>
            <div className='grid gap-4 md:grid-cols-2 xl:grid-cols-5'>
              {pillars.map((pillar, index) => (
                <article
                  key={pillar.title}
                  className={`group rounded-[1.75rem] border p-6 transition hover:-translate-y-1 hover:border-cyan-200/40 hover:bg-white/10 ${
                    activePillarTitle === pillar.title
                      ? 'border-cyan-200/50 bg-cyan-200/10 shadow-2xl shadow-cyan-950/30'
                      : 'border-white/10 bg-slate-950/40'
                  }`}
                >
                  <button
                    type='button'
                    onClick={() => handlePillarPreview(pillar)}
                    className='block w-full text-left focus:outline-none focus:ring-4 focus:ring-cyan-300/30'
                  >
                    <div className='mb-8 flex h-12 w-12 items-center justify-center rounded-2xl bg-gradient-to-br from-[#1DE9B6] to-[#6C63FF] text-lg font-black text-slate-950'>
                      {index + 1}
                    </div>
                    <h3 className='text-xl font-bold'>{pillar.title}</h3>
                    <p className='mt-3 text-sm leading-6 text-slate-300'>
                      {pillar.description}
                    </p>
                  </button>
                  <div className='mt-6 flex flex-col gap-2'>
                    <BaseButton
                      href={pillar.route}
                      label={pillar.actionLabel}
                      color={index === 0 ? 'success' : 'white'}
                      outline={index !== 0}
                      roundedFull
                      small
                      className={
                        index === 0
                          ? 'border-emerald-300 bg-[#1DE9B6] text-slate-950 hover:bg-white'
                          : 'border-white/20 bg-white/5 text-white hover:bg-white hover:text-slate-950'
                      }
                    />
                    <BaseButton
                      onClick={() => handlePillarPreview(pillar)}
                      label='Preview di halaman ini'
                      color='white'
                      outline
                      roundedFull
                      small
                      className='border-white/20 bg-transparent text-slate-200 hover:bg-white/10'
                    />
                  </div>
                </article>
              ))}
            </div>
          </div>
        </section>


        <section id='commerce-detail' className='px-5 py-20 sm:px-8 lg:px-12'>
          <div className='mx-auto max-w-7xl'>
            <div className='grid gap-8 lg:grid-cols-[0.95fr_1.05fr] lg:items-start'>
              <div className='rounded-[2rem] border border-emerald-300/20 bg-emerald-300/10 p-6 shadow-2xl shadow-emerald-950/20'>
                <p className='text-sm font-semibold tracking-[0.28em] text-[#1DE9B6]'>
                  1. VORTA Commerce
                </p>
                <h2 className='mt-3 text-3xl font-black md:text-5xl'>
                  Platform Perdagangan, Distribusi, Komunitas, dan Pembayaran Berbasis Kepercayaan
                </h2>
                <p className='mt-5 text-sm leading-7 text-slate-200 md:text-base'>
                  VORTA Commerce adalah platform utama dalam ekosistem VORTA Universe yang menghubungkan pembeli, penjual, UMKM, kreator, perusahaan, komunitas, afiliator, dan mitra logistik melalui sistem perdagangan berbasis kepercayaan (Trust-Based Commerce). VORTA Commerce tidak hanya berfungsi sebagai marketplace, tetapi juga sebagai pusat aktivitas bisnis digital yang menggabungkan perdagangan, distribusi, afiliasi, logistik, komunikasi, komunitas, dan pembayaran dalam satu platform terpadu. Dengan dukungan VORTA Nexus Trust Score, setiap identitas, toko, produk, ulasan, transaksi, dan aktivitas komunitas memiliki tingkat kepercayaan yang dapat diukur dan diverifikasi.
                </p>
                <div className='mt-6 rounded-3xl border border-white/10 bg-white/[0.08] p-5'>
                  <p className='text-xs font-black uppercase tracking-[0.22em] text-emerald-200'>
                    Visi
                  </p>
                  <p className='mt-3 text-sm leading-7 text-slate-200'>{commerceVision}</p>
                </div>
              </div>

              <div className='space-y-5'>
                <div className='rounded-[2rem] border border-white/10 bg-slate-950/50 p-6'>
                  <p className='text-xs font-black uppercase tracking-[0.22em] text-cyan-200'>
                    Misi
                  </p>
                  <div className='mt-4 grid gap-3 sm:grid-cols-2'>
                    {commerceMission.map((mission) => (
                      <div
                        key={mission}
                        className='rounded-2xl border border-white/10 bg-white/[0.06] px-4 py-3 text-sm leading-6 text-slate-200'
                      >
                        {mission}
                      </div>
                    ))}
                  </div>
                </div>

                <div className='grid gap-4 md:grid-cols-2'>
                  {commercePillars.map((pillar, index) => (
                    <article
                      key={pillar.title}
                      className='rounded-[1.5rem] border border-white/10 bg-white/[0.06] p-5'
                    >
                      <div className='mb-4 inline-flex h-10 w-10 items-center justify-center rounded-2xl bg-gradient-to-br from-[#1DE9B6] to-[#6C63FF] text-sm font-black text-slate-950'>
                        {index + 1}
                      </div>
                      <h3 className='text-lg font-black'>{pillar.title}</h3>
                      <p className='mt-2 text-sm text-slate-300'>{pillar.description}</p>
                      <div className='mt-4 flex flex-wrap gap-2'>
                        {pillar.features.map((feature) => (
                          <span
                            key={feature}
                            className='rounded-full border border-white/10 bg-white/[0.08] px-3 py-1 text-xs font-semibold text-cyan-100'
                          >
                            {feature}
                          </span>
                        ))}
                      </div>
                    </article>
                  ))}
                </div>
              </div>
            </div>
          </div>
        </section>

        <section id='trust-flow' className='px-5 py-20 sm:px-8 lg:px-12'>
          <div className='mx-auto grid max-w-7xl gap-8 lg:grid-cols-[0.9fr_1.1fr]'>
            <div className='lg:sticky lg:top-8 lg:self-start'>
              <p className='text-sm font-semibold tracking-[0.28em] text-[#1DE9B6]'>
                Mesin kepercayaan bawaan
              </p>
              <h2 className='mt-3 text-4xl font-black'>
                Skor Kepercayaan untuk Super-App
              </h2>
              <p className='mt-4 text-slate-300'>
                Setiap akun, toko, percakapan, ulasan, dan transaksi bisa diberi
                sinyal kepercayaan agar marketplace dan komunitas tetap aman
                tanpa terasa berat bagi pengguna.
              </p>
              <div className='mt-6 rounded-3xl border border-white/10 bg-white/[0.08] p-5 text-sm leading-6 text-slate-300'>
                <strong className='text-white'>Aturan validasi:</strong> nama
                profil wajib minimal 3 karakter. Skor 31+ menandakan profil
                layak masuk feed sosial, chat bisnis, dan marketplace publik.
              </div>
            </div>

            <CardBox
              className='border-white/10 bg-white text-slate-950 shadow-2xl shadow-cyan-950/20'
              cardBoxClassName='p-0'
            >
              <form onSubmit={handleSubmit} className='p-6 md:p-8'>
                <div className='grid gap-5 md:grid-cols-2'>
                  <label className='md:col-span-2'>
                    <span className='mb-2 block text-sm font-bold text-slate-700'>
                      Nama profil
                    </span>
                    <input
                      value={form.profileName}
                      onChange={(event) =>
                        updateField('profileName', event.target.value)
                      }
                      className='w-full rounded-2xl border border-slate-200 bg-slate-50 px-4 py-3 outline-none transition focus:border-cyan-400 focus:ring-4 focus:ring-cyan-100'
                      placeholder='Contoh: Warung Nusantara Bandung'
                    />
                  </label>

                  <label>
                    <span className='mb-2 block text-sm font-bold text-slate-700'>
                      Tipe profil
                    </span>
                    <select
                      value={form.profileType}
                      onChange={(event) =>
                        updateField(
                          'profileType',
                          event.target.value as TrustForm['profileType'],
                        )
                      }
                      className='w-full rounded-2xl border border-slate-200 bg-slate-50 px-4 py-3 outline-none transition focus:border-cyan-400 focus:ring-4 focus:ring-cyan-100'
                    >
                      <option value='creator'>Kreator / edukator</option>
                      <option value='umkm'>UMKM / penjual lokal</option>
                      <option value='company'>Perusahaan / rekruter</option>
                    </select>
                  </label>

                  <label>
                    <span className='mb-2 block text-sm font-bold text-slate-700'>
                      Dokumen terverifikasi
                    </span>
                    <input
                      type='number'
                      min='0'
                      max='4'
                      value={form.verifiedDocuments}
                      onChange={(event) =>
                        updateField('verifiedDocuments', event.target.value)
                      }
                      className='w-full rounded-2xl border border-slate-200 bg-slate-50 px-4 py-3 outline-none transition focus:border-cyan-400 focus:ring-4 focus:ring-cyan-100'
                    />
                  </label>

                  <label>
                    <span className='mb-2 block text-sm font-bold text-slate-700'>
                      Deep Dive Links valid
                    </span>
                    <input
                      type='number'
                      min='0'
                      max='5'
                      value={form.citedSources}
                      onChange={(event) =>
                        updateField('citedSources', event.target.value)
                      }
                      className='w-full rounded-2xl border border-slate-200 bg-slate-50 px-4 py-3 outline-none transition focus:border-cyan-400 focus:ring-4 focus:ring-cyan-100'
                    />
                  </label>
                </div>

                <div className='mt-6 grid gap-3 md:grid-cols-2'>
                  {[
                    ['hasBiometric', 'Pencocokan wajah biometrik aktif'],
                    ['hasTaxId', 'NPWP / legalitas bisnis valid'],
                    ['hasTransactionHistory', 'Riwayat transaksi bersih'],
                    ['verifiedReviews', 'Ulasan dikunci oleh bukti bayar'],
                    ['localPresence', 'Lokasi nyata / geofence aktif'],
                  ].map(([field, label]) => (
                    <label
                      key={field}
                      className='flex items-center gap-3 rounded-2xl border border-slate-200 bg-slate-50 px-4 py-3 text-sm font-semibold text-slate-700'
                    >
                      <input
                        type='checkbox'
                        checked={Boolean(form[field as keyof TrustForm])}
                        onChange={(event) =>
                          updateField(
                            field as keyof TrustForm,
                            event.target.checked,
                          )
                        }
                        className='h-5 w-5 rounded border-slate-300 text-cyan-500 focus:ring-cyan-400'
                      />
                      {label}
                    </label>
                  ))}
                </div>

                {errorMessage ? (
                  <div className='mt-5 rounded-2xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm font-semibold text-rose-700'>
                    {errorMessage}
                  </div>
                ) : null}

                <div className='mt-7 flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between'>
                  <p className='text-sm text-slate-500'>
                    Laporan tersimpan di browser ini sebagai riwayat demo MVP.
                  </p>
                  <div className='flex flex-col gap-2 sm:flex-row'>
                    <BaseButton
                      onClick={handleSampleReport}
                      label='Buat Contoh Cepat'
                      color='white'
                      outline
                      roundedFull
                      className='border-slate-300 px-5 py-3 text-slate-700 hover:bg-slate-100'
                    />
                    <BaseButton
                      onClick={handleResetForm}
                      label='Reset Formulir'
                      color='white'
                      outline
                      roundedFull
                      className='border-slate-300 px-5 py-3 text-slate-700 hover:bg-slate-100'
                    />
                    <BaseButton
                      type='submit'
                      label='Buat Laporan Kepercayaan'
                      color='info'
                      roundedFull
                      className='bg-slate-950 px-6 py-3 text-white hover:bg-cyan-600'
                    />
                  </div>
                </div>
              </form>
            </CardBox>
          </div>
        </section>

        <section id='reports' className='px-5 pb-20 sm:px-8 lg:px-12'>
          <div className='mx-auto grid max-w-7xl gap-8 lg:grid-cols-[0.9fr_1.1fr]'>
            <CardBox
              className='border-white/10 bg-white/[0.08] text-white backdrop-blur'
              cardBoxClassName='p-0'
            >
              <div className='border-b border-white/10 p-6'>
                <h2 className='text-2xl font-black'>
                  Daftar Laporan Kepercayaan
                </h2>
                <p className='mt-2 text-sm text-slate-300'>
                  Pilih laporan untuk membuka detail simulasi.
                </p>
                <div className='mt-4 flex flex-wrap gap-2'>
                  <BaseButton
                    onClick={handleSampleReport}
                    label='Jalankan Contoh'
                    color='white'
                    outline
                    roundedFull
                    small
                    className='border-white/20 bg-white/5 text-white hover:bg-white hover:text-slate-950'
                  />
                  <BaseButton
                    onClick={handleClearReports}
                    label='Bersihkan Laporan'
                    color='danger'
                    outline
                    roundedFull
                    small
                    className='border-rose-200/40 bg-rose-300/10 text-rose-100 hover:bg-rose-200 hover:text-slate-950'
                  />
                </div>
              </div>
              <div className='space-y-3 p-4'>
                {reports.length ? (
                  reports.map((report) => (
                    <button
                      key={report.id}
                      type='button'
                      onClick={() => setActiveReportId(report.id)}
                      className={`w-full rounded-3xl border p-4 text-left transition focus:outline-none focus:ring-4 focus:ring-cyan-300/30 ${activeReport?.id === report.id ? 'border-cyan-300 bg-cyan-300/15' : 'border-white/10 bg-slate-950/30 hover:border-white/30 hover:bg-white/10'}`}
                    >
                      <div className='flex items-start justify-between gap-3'>
                        <div>
                          <p className='font-bold'>{report.profileName}</p>
                          <p className='mt-1 text-xs uppercase tracking-[0.18em] text-slate-400'>
                            {profileTypeLabels[report.profileType]} ·{' '}
                            {new Date(report.createdAt).toLocaleDateString(
                              'id-ID',
                            )}
                          </p>
                        </div>
                        <span className='rounded-full bg-white px-3 py-1 text-sm font-black text-slate-950'>
                          {report.score}
                        </span>
                      </div>
                    </button>
                  ))
                ) : (
                  <div className='rounded-3xl border border-dashed border-white/20 p-8 text-center text-slate-300'>
                    <p>
                      Belum ada laporan. Isi simulator di atas untuk membuat
                      Laporan Kepercayaan pertama.
                    </p>
                    <button
                      type='button'
                      onClick={handleSampleReport}
                      className='mt-5 rounded-full bg-cyan-300 px-5 py-2 text-sm font-bold text-slate-950 transition hover:bg-white focus:outline-none focus:ring-4 focus:ring-cyan-300/30'
                    >
                      Buat Contoh Laporan
                    </button>
                  </div>
                )}
              </div>
            </CardBox>

            <CardBox
              className='border-white/10 bg-white text-slate-950 shadow-2xl shadow-black/20'
              cardBoxClassName='p-0'
            >
              {activeReport ? (
                <div>
                  <div
                    className={`rounded-t-2xl bg-gradient-to-br ${scoreGradient(activeReport.score)} p-8 text-slate-950`}
                  >
                    <p className='text-sm font-black uppercase tracking-[0.25em] opacity-70'>
                      Detail Laporan Kepercayaan
                    </p>
                    <div className='mt-6 flex flex-col gap-6 sm:flex-row sm:items-end sm:justify-between'>
                      <div>
                        <h2 className='text-3xl font-black'>
                          {activeReport.profileName}
                        </h2>
                        <p className='mt-2 font-semibold'>
                          {getTier(activeReport.score)}
                        </p>
                      </div>
                      <div className='text-7xl font-black leading-none'>
                        {activeReport.score}
                      </div>
                    </div>
                    <div className='mt-7 h-3 rounded-full bg-slate-950/25'>
                      <div
                        className='h-3 rounded-full bg-slate-950'
                        style={{ width: `${activeReport.score}%` }}
                      />
                    </div>
                  </div>

                  <div className='grid gap-6 p-6 md:grid-cols-2 md:p-8'>
                    <div className='rounded-3xl bg-slate-50 p-5'>
                      <h3 className='font-black'>Ringkasan sinyal</h3>
                      <dl className='mt-4 space-y-3 text-sm'>
                        <div className='flex justify-between gap-4'>
                          <dt className='text-slate-500'>Dokumen</dt>
                          <dd className='font-bold'>
                            {activeReport.verifiedDocuments}/4
                          </dd>
                        </div>
                        <div className='flex justify-between gap-4'>
                          <dt className='text-slate-500'>Deep Dive Links</dt>
                          <dd className='font-bold'>
                            {activeReport.citedSources}/5
                          </dd>
                        </div>
                        <div className='flex justify-between gap-4'>
                          <dt className='text-slate-500'>Akses Pulse</dt>
                          <dd className='font-bold'>
                            {activeReport.score >= 31
                              ? 'Memenuhi syarat'
                              : 'Terkunci'}
                          </dd>
                        </div>
                        <div className='flex justify-between gap-4'>
                          <dt className='text-slate-500'>Integritas ulasan</dt>
                          <dd className='font-bold'>
                            {activeReport.verifiedReviews
                              ? 'Terlindungi'
                              : 'Terbuka'}
                          </dd>
                        </div>
                      </dl>
                    </div>
                    <div className='rounded-3xl bg-slate-950 p-5 text-white'>
                      <h3 className='font-black'>Aksi terbaik berikutnya</h3>
                      <ul className='mt-4 space-y-3 text-sm text-slate-300'>
                        {activeReport.recommendations.map((recommendation) => (
                          <li key={recommendation} className='flex gap-3'>
                            <span className='mt-1 h-2 w-2 flex-none rounded-full bg-[#1DE9B6]' />
                            <span>{recommendation}</span>
                          </li>
                        ))}
                      </ul>
                    </div>
                  </div>
                </div>
              ) : (
                <div className='p-10 text-center'>
                  <div className='mx-auto mb-5 grid h-16 w-16 place-items-center rounded-3xl bg-slate-100 text-2xl'>
                    🛡️
                  </div>
                  <h2 className='text-2xl font-black'>
                    Detail laporan akan muncul di sini
                  </h2>
                  <p className='mt-3 text-slate-500'>
                    Buat Laporan Kepercayaan pertama untuk melihat tier,
                    progress bar, dan rekomendasi.
                  </p>
                  <BaseButton
                    onClick={handleSampleReport}
                    label='Buat Contoh Sekarang'
                    color='info'
                    roundedFull
                    className='mt-6 bg-slate-950 text-white hover:bg-cyan-600'
                  />
                </div>
              )}
            </CardBox>
          </div>
        </section>

        <footer className='border-t border-white/10 px-5 py-8 text-sm text-slate-400 sm:px-8 lg:px-12'>
          <div className='mx-auto flex max-w-7xl flex-col gap-4 md:flex-row md:items-center md:justify-between'>
            <p>
              © 2026 VORTA Universe MVP. Urutan utama dimulai dari 1. VORTA Commerce, lalu Synapse, Super-App, Nexus, dan Facta.Ai.
            </p>
            <div className='flex gap-5'>
              <Link href='/privacy-policy/' className='hover:text-white'>
                Kebijakan Privasi
              </Link>
              <Link href='/terms-of-use/' className='hover:text-white'>
                Ketentuan Penggunaan
              </Link>
              <Link
                href='/login'
                className='font-semibold text-cyan-200 hover:text-white'
              >
                Panel Admin
              </Link>
            </div>
          </div>
        </footer>
      </main>
    </>
  );
}

VortaLanding.getLayout = function getLayout(page: ReactElement) {
  return <LayoutGuest>{page}</LayoutGuest>;
};
