'use client'
import { useState } from 'react'
import { useT } from '@/contexts/LangContext'
import Box from '@mui/material/Box'
import Card from '@mui/material/Card'
import CardContent from '@mui/material/CardContent'
import Typography from '@mui/material/Typography'
import Tab from '@mui/material/Tab'
import Tabs from '@mui/material/Tabs'
import Chip from '@mui/material/Chip'
import Tooltip from '@mui/material/Tooltip'
import Divider from '@mui/material/Divider'

// ── Types ─────────────────────────────────────────────────────────────────────

type Support = 'yes' | 'partial' | 'no' | 'planned'

interface Feature {
  key:          string
  note?:        string
  soi:          Support
  soinote?:     string
  tabs:         Support
  tabsnote?:    string
  trek:         Support
  treknote?:    string
  lexring:      Support
  lexringnote?: string
}

interface Category {
  id:       string
  icon:     string
  features: Feature[]
}

// ── Pricing plans ─────────────────────────────────────────────────────────────

const SOI_PLAN_KEYS = [
  {
    nameKey:      'planSolo' as const,
    monthlyPrice: '฿2,350',
    annualPrice:  '฿1,990',
    savePct:      15,
    seatKey: 'seatAtty1' as const,
    highlight: false,
    featureKeys: ['soloF1','soloF2','soloF3','soloF4','soloF5','soloF6','soloF7'] as const,
    notIncludedKeys: ['soloNI1','soloNI2','soloNI3'] as const,
  },
  {
    nameKey:      'planFirm' as const,
    monthlyPrice: '฿4,990',
    annualPrice:  '฿3,990',
    savePct:      20,
    seatKey: 'seatUpTo5' as const,
    highlight: true,
    featureKeys: ['firmF1','firmF2','firmF3','firmF4','firmF5','firmF6'] as const,
    notIncludedKeys: ['firmNI1','firmNI2'] as const,
  },
  {
    nameKey:      'planComplete' as const,
    monthlyPrice: '฿7,990',
    annualPrice:  '฿5,990',
    savePct:      25,
    seatKey: 'seatUnlimited' as const,
    highlight: false,
    featureKeys: ['completeF1','completeF2','completeF3','completeF4','completeF5','completeF6','completeF7'] as const,
    notIncludedKeys: [] as const,
  },
]

// Cost at N users for a real comparison
const COST_SCENARIOS = [
  { labelKey: 'seatAtty1' as const, soi: '฿2,350',  tabs: '$89 / ~฿3,200',   trek: '฿1,500–3,000', lexring: '฿1,800–2,500' },
  { labelKey: 'seatUpTo5' as const, soi: '฿4,990',  tabs: '$267 / ~฿9,600',  trek: '฿4,500–9,000', lexring: '฿5,400–7,500' },
  { labelKey: 'seatUnlimited' as const, soi: '฿7,990', tabs: '$445 / ~฿16,000', trek: '฿7,500–15,000', lexring: '฿9,000–12,500' },
]

// ── Data ──────────────────────────────────────────────────────────────────────

const CATEGORIES: Category[] = [
  {
    id: 'practice',
    icon: 'ri-briefcase-4-line',
    features: [
      { key: 'fMatterTracking',       soi: 'yes', tabs: 'yes', trek: 'yes', lexring: 'yes' },
      { key: 'fClientFolderMgmt',     soi: 'yes', tabs: 'yes', trek: 'yes', lexring: 'yes' },
      {
        key: 'fMatterStatusWorkflow',
        soi: 'yes', soinote: 'Flowchart workflow builder — drag-and-drop step editor with deadlines, mandatory flags, and linked forms. Assign multiple workflows per matter. 10 stock templates seeded on startup.',
        tabs: 'partial', tabsnote: 'Status fields only — no workflow engine',
        trek: 'yes', lexring: 'partial', lexringnote: 'Status fields; limited workflow automation',
      },
      {
        key: 'fWorkflowBuilder',
        soi: 'yes', soinote: 'Visual node-graph editor (React Flow) — add/reorder steps, set deadline days, mark mandatory, link form templates. Save as reusable template or clone for a specific matter.',
        tabs: 'no', trek: 'no', lexring: 'no',
      },
      {
        key: 'fObligationTimeline',
        soi: 'yes', soinote: 'Obligation timeline auto-generates compliance deadlines from anchor dates (arrival, visa expiry, permit expiry). 8 stock Thai legal obligation rules (TM.47, TM.7, work permit, AGM, etc.) seeded on startup.',
        tabs: 'partial', tabsnote: 'Manual calendar reminders only — no rule engine',
        trek: 'partial', treknote: 'Date reminders only — no obligation rule engine',
        lexring: 'partial', lexringnote: 'Date reminders only',
      },
      {
        key: 'fPracticeAreaTemplates',
        soi: 'yes', soinote: 'Immigration, BOI, civil litigation, property, employment, family, criminal',
        tabs: 'partial', tabsnote: 'US law templates — not applicable to Thai practice',
        trek: 'partial', treknote: 'Generic Thai templates — limited depth',
        lexring: 'partial', lexringnote: 'Thai templates for civil and criminal — no immigration/BOI specifics',
      },
      {
        key: 'fThaiCourtMgmt',
        soi: 'yes', soinote: 'Hearing types, court divisions, Thai judge/officer fields',
        tabs: 'no', tabsnote: 'US courts only',
        trek: 'yes', lexring: 'yes', lexringnote: 'Thai court hearings and divisions',
      },
      {
        key: 'fConflictCheck',
        soi: 'yes', soinote: 'Automated party + name scan across all client folders',
        tabs: 'partial', tabsnote: 'Separate add-on module — extra cost',
        trek: 'partial', treknote: 'Manual name search only',
        lexring: 'partial', lexringnote: 'Manual search only — no automated scan',
      },
      { key: 'fCourtHearingCalendar', soi: 'yes', tabs: 'yes', trek: 'yes', lexring: 'yes' },
      {
        key: 'fPartyDirectory',
        soi: 'yes', soinote: 'Roles: client, opposing party, opposing counsel, witness, judge, court officer, co-counsel',
        tabs: 'partial', tabsnote: 'Contact list — no role taxonomy',
        trek: 'partial', treknote: 'Basic contact list',
        lexring: 'partial', lexringnote: 'Contact list — limited role taxonomy',
      },
      {
        key: 'fJudicialIntel',
        soi: 'yes', soinote: 'Career-long profiles on judges and court support staff. Deepens across all matters regardless of client',
        tabs: 'no', trek: 'no', lexring: 'no',
      },
      {
        key: 'fAdversaryIntel',
        soi: 'yes', soinote: 'Per-counsel and per-firm profiles. Updated at every matter close — compounds as a strategic moat',
        tabs: 'no', trek: 'no', lexring: 'no',
      },
      { key: 'fMultiMatterView',      soi: 'yes', tabs: 'yes', trek: 'yes', lexring: 'yes' },
      {
        key: 'fCrossMatterIntel',
        soi: 'yes', soinote: 'Case Analyst queries Client Manager + Judicial Intel + Adversary Intel + RAG Agent in parallel → full strategic brief',
        tabs: 'no', trek: 'no', lexring: 'no',
      },
      {
        key: 'fBoiImmigration',
        soi: 'yes', soinote: 'Practice-area fields, TM.7 / BOI zone / visa type tracking',
        tabs: 'no', tabsnote: 'No Thailand-specific modules',
        trek: 'partial', treknote: 'Basic immigration matter type only',
        lexring: 'no', lexringnote: 'No immigration/BOI-specific modules',
      },
      {
        key: 'fMatterRefInComms',
        soi: 'yes', soinote: 'Auto-prefixed: [ref: matterNumber] on all outbound emails — enables auto-threading on reply',
        tabs: 'no', trek: 'no', lexring: 'no',
      },
    ],
  },

  {
    id: 'ai',
    icon: 'ri-sparkling-2-line',
    features: [
      {
        key: 'fAiAssistant',
        soi: 'yes', soinote: 'Prompt Analyst — conversational, tool-use loop, session memory, live DB access',
        tabs: 'no', trek: 'no', lexring: 'no',
      },
      {
        key: 'fMultiAgentHierarchy',
        soi: 'yes', soinote: '10 agents — Prompt Analyst, Onboarding, Document Classifier, Case Analyst, Client Manager(×N), Comms, RAG, Billing, Judicial Intel, Adversary Intel',
        tabs: 'no', trek: 'no', lexring: 'no',
      },
      {
        key: 'fEmailTriageRouting',
        soi: 'yes', soinote: '4-level engine: thread inheritance → exact email match → display name fuzzy → open matter scan',
        tabs: 'no', trek: 'no', lexring: 'no',
      },
      {
        key: 'fDocClassification',
        soi: 'yes', soinote: 'Document Classifier agent — bilingual Thai/English, identifies document type and recommended action',
        tabs: 'no', trek: 'no', lexring: 'no',
      },
      {
        key: 'fRagLookup',
        soi: 'yes', soinote: 'RAG Agent receives a precision-framed query — domain already established by Classifier before the lookup',
        tabs: 'no', trek: 'no', lexring: 'no',
      },
      {
        key: 'fPerClientAgent',
        soi: 'yes', soinote: 'One agent per client — knows that client completely. Depth compounds over the client lifecycle',
        tabs: 'no', trek: 'no', lexring: 'no',
      },
      {
        key: 'fAiMatterBrief',
        soi: 'yes', soinote: 'Client history + judge profile + opposing counsel + applicable statutes + retainer status — all assembled at matter open',
        tabs: 'no', trek: 'no', lexring: 'no',
      },
      {
        key: 'fAiBillingQuote',
        soi: 'yes', soinote: 'Billing Agent receives matter type + complexity from Case Analyst → returns quote figure. Attorney approval gate above threshold',
        tabs: 'no', trek: 'no', lexring: 'no',
      },
      {
        key: 'fProactiveAlerts',
        soi: 'yes', soinote: 'Client Manager monitors each client → escalates to Case Analyst → Comms Agent dispatches alerts. Obligation timeline generates compliance deadlines from anchor dates — no attorney prompt needed.',
        tabs: 'partial', tabsnote: 'Rule-based date reminders only — no intelligence',
        trek: 'partial', treknote: 'Email reminders on set dates — no intelligence',
        lexring: 'partial', lexringnote: 'Rule-based date reminders only',
      },
      {
        key: 'fOnboardingAgent',
        soi: 'yes', soinote: 'All new data (manual or automated) flows through Onboarding Agent → Prompt Analyst. Never writes directly to client records',
        tabs: 'no', trek: 'no', lexring: 'no',
      },
      {
        key: 'fAttorneyApproval',
        soi: 'yes', soinote: 'High-value actions (quotes above threshold, outbound client comms) require attorney sign-off before dispatch. AI-proposed deadlines follow Forecast → Confirm → Learn: attorney confirms, edits, or rejects each proposal — all deltas captured as fine-tuning signals.',
        tabs: 'no', trek: 'no', lexring: 'no',
      },
      {
        key: 'fForecastConfirmLearn',
        soi: 'yes', soinote: 'Every attorney edit to a proposed deadline (date change, note) and every rejection (with reason) is logged as editDelta / rejectionReason — feeds the weekly fine-tuning pipeline to improve future proposals over time.',
        tabs: 'no', trek: 'no', lexring: 'no',
      },
      {
        key: 'fIntelligenceCompounds',
        soi: 'yes', soinote: 'Judicial and Adversary profiles deepen at every matter close — strategic moat that grows regardless of client return rate',
        tabs: 'no', trek: 'no', lexring: 'no',
      },
      {
        key: 'fThaiAiHandling',
        soi: 'yes', soinote: 'Document Classifier handles Thai-language documents from day one',
        tabs: 'no', tabsnote: 'English only',
        trek: 'partial', treknote: 'Thai UI — no AI on Thai documents',
        lexring: 'no', lexringnote: 'No AI on documents',
      },
    ],
  },

  {
    id: 'comms',
    icon: 'ri-mail-line',
    features: [
      {
        key: 'fImapPolling',
        soi: 'yes', soinote: 'imapflow — configurable host/port/SSL/interval. Marks \\Seen after ingestion to prevent re-import',
        tabs: 'partial', tabsnote: 'Outlook plugin only — no independent IMAP',
        trek: 'no', lexring: 'partial', lexringnote: 'Basic IMAP connection — no routing or threading',
      },
      {
        key: 'fSmtpRelay',
        soi: 'yes', soinote: 'Configurable relay with sender identity separate from SMTP credentials',
        tabs: 'partial', tabsnote: 'Via Outlook / Exchange — no built-in SMTP',
        trek: 'no', lexring: 'partial', lexringnote: 'Via Gmail/Outlook connect — no independent SMTP',
      },
      {
        key: 'fSmtpListener',
        soi: 'yes', soinote: 'Platform accepts delivery on port 2525 — no forwarding needed',
        tabs: 'no', trek: 'no', lexring: 'no',
      },
      {
        key: 'fEmailThreadedToMatter',
        soi: 'yes', soinote: 'All emails linked via [ref: matterNumber] subject prefix — replies auto-associate to the same thread',
        tabs: 'no', trek: 'no', lexring: 'no',
      },
      {
        key: 'fFirmInbox',
        soi: 'yes', soinote: 'Pending / needs routing / inbound / outbound / email setup tabs',
        tabs: 'no', trek: 'no', lexring: 'no',
      },
      {
        key: 'fPerClientCommsTab',
        soi: 'yes', soinote: 'Thread list + detail pane per client folder — filtered by matter',
        tabs: 'no', trek: 'no',
        lexring: 'partial', lexringnote: 'Email log per client — no threading',
      },
      {
        key: 'fComposeReply',
        soi: 'yes', soinote: 'Subject auto-prefixed with matter ref; from address selector',
        tabs: 'no', trek: 'no',
        lexring: 'partial', lexringnote: 'Basic compose — no matter ref prefix',
      },
      {
        key: 'fEmailAssocEngine',
        soi: 'yes', soinote: '4-level — thread → email address → display name → open matter scan. Surfaces candidates for attorney confirmation when ambiguous',
        tabs: 'no', trek: 'no', lexring: 'no',
      },
      {
        key: 'fLineIntegration',
        soi: 'planned', soinote: 'Phase 2 — Comms Agent',
        tabs: 'no',
        trek: 'partial', treknote: 'LINE Notify send-only — no reply',
        lexring: 'no',
      },
      {
        key: 'fGoogleCalendarSync',
        soi: 'planned', soinote: 'Phase 2 — Comms Agent via OAuth + webhook',
        tabs: 'partial', tabsnote: 'iCal export only',
        trek: 'partial', treknote: 'Export only',
        lexring: 'partial', lexringnote: 'iCal export only',
      },
      {
        key: 'fClientPortal',
        soi: 'planned', soinote: 'Phase 3',
        tabs: 'no', trek: 'no', lexring: 'no',
      },
    ],
  },

  {
    id: 'billing',
    icon: 'ri-money-dollar-circle-line',
    features: [
      { key: 'fTimeEntryLogging', soi: 'yes', tabs: 'yes', trek: 'yes', lexring: 'yes' },
      { key: 'fExpenseTracking',  soi: 'yes', tabs: 'yes', trek: 'yes', lexring: 'yes' },
      { key: 'fInvoicePdf',       soi: 'yes', tabs: 'yes', trek: 'yes', lexring: 'yes' },
      {
        key: 'fMultiBillingTypes',
        soi: 'yes', soinote: 'Hourly, flat fee, retainer, contingency — multi-type array per client; overridable per matter',
        tabs: 'yes', tabsnote: 'Hourly, flat, contingency',
        trek: 'partial', treknote: 'Hourly and flat fee only',
        lexring: 'partial', lexringnote: 'Hourly and flat fee only',
      },
      {
        key: 'fTrustRetainerMgmt',
        soi: 'yes', soinote: 'Full trust ledger with deposit, disbursement, and reconciliation',
        tabs: 'yes', tabsnote: 'TABS3 Trust is one of its strongest features — full three-way reconciliation',
        trek: 'partial', treknote: 'Basic retainer balance — no trust accounting rules',
        lexring: 'partial', lexringnote: 'Basic retainer tracking only',
      },
      {
        key: 'fMultiCurrencyBilling',
        soi: 'yes', soinote: '~95 ISO currencies with full selector',
        tabs: 'partial', tabsnote: 'USD primary; limited foreign currency',
        trek: 'partial', treknote: 'THB + USD only',
        lexring: 'partial', lexringnote: 'THB only',
      },
      {
        key: 'fArOverdueTracking',
        soi: 'yes',
        tabs: 'yes', tabsnote: 'TABS3 Accounts Receivable is a core module — strong',
        trek: 'yes', lexring: 'yes',
      },
      {
        key: 'fBillingSchedule',
        soi: 'yes', soinote: 'Next billing date + recurring schedule date chips per client',
        tabs: 'partial', tabsnote: 'Statement cycles — not per-client schedule dates',
        trek: 'no', lexring: 'partial', lexringnote: 'Manual billing date only — no recurring schedule',
      },
      {
        key: 'fRetainerTopupAlerts',
        soi: 'yes', soinote: 'Comms Agent proactively alerts when balance nears threshold — no attorney prompt needed',
        tabs: 'partial', tabsnote: 'Manual low-balance report — no automated alert',
        trek: 'partial', treknote: 'Manual check',
        lexring: 'partial', lexringnote: 'Dashboard indicator only — no automated alert',
      },
      {
        key: 'fAiBillingAgent',
        soi: 'yes', soinote: 'Receives matter type + complexity from Case Analyst; returns figure with attorney approval gate above threshold',
        tabs: 'no', trek: 'no', lexring: 'no',
      },
      {
        key: 'fClientBillingNotes',
        soi: 'yes', soinote: 'Billing note field visible on invoices for that matter',
        tabs: 'yes',
        trek: 'partial', treknote: 'Generic memo field only',
        lexring: 'partial', lexringnote: 'Generic notes field only',
      },
      {
        key: 'fGeneralLedger',
        soi: 'no', soinote: 'Out of scope — integrates with external accounting software',
        tabs: 'yes', tabsnote: 'TABS3 General Ledger module — full double-entry bookkeeping',
        trek: 'no', lexring: 'no',
      },
      {
        key: 'fChequeWriting',
        soi: 'no',
        tabs: 'yes', tabsnote: 'Check writing module — prints trust and operating cheques',
        trek: 'no', lexring: 'no',
      },
      {
        key: 'fBankReconciliation',
        soi: 'no',
        tabs: 'yes', tabsnote: 'Bank reconciliation built into trust module',
        trek: 'no', lexring: 'no',
      },
    ],
  },

  {
    id: 'documents',
    icon: 'ri-file-text-line',
    features: [
      { key: 'fDocUpload',       soi: 'yes', tabs: 'yes', trek: 'yes', lexring: 'yes' },
      { key: 'fDocLinkedToMatter', soi: 'yes', tabs: 'yes', trek: 'yes', lexring: 'yes' },
      {
        key: 'fDocTypesMetadata',
        soi: 'yes', soinote: 'Type, category, linked matter, party, date, notes',
        tabs: 'partial', tabsnote: 'Limited metadata',
        trek: 'partial', treknote: 'Type and date only',
        lexring: 'partial', lexringnote: 'Type and date only',
      },
      {
        key: 'fAiDocClassification',
        soi: 'yes', soinote: 'Document Classifier identifies type, matter ref, practice area, recommended action — bilingual',
        tabs: 'no', trek: 'no', lexring: 'no',
      },
      {
        key: 'fThaiDocSupport',
        soi: 'yes', soinote: 'Native — Classifier handles Thai from day one',
        tabs: 'no', tabsnote: 'English only',
        trek: 'partial', treknote: 'Storage only — no Thai OCR/classification',
        lexring: 'partial', lexringnote: 'Storage only — no Thai OCR',
      },
      { key: 'fPdfGeneration', soi: 'yes', tabs: 'yes', trek: 'yes', lexring: 'yes' },
      {
        key: 'fDocTemplates',
        soi: 'yes', soinote: 'Form template library per practice area — upload PDF, calibrate field positions, generate pre-filled PDFs. View Form button previews raw PDF. Custom upload per firm.',
        tabs: 'yes', tabsnote: 'Integrated with Word via PracticeMaster',
        trek: 'partial', treknote: 'Limited Thai court templates',
        lexring: 'partial', lexringnote: 'Basic Thai court templates',
      },
      {
        key: 'fVersionControl',
        soi: 'planned',
        tabs: 'partial', tabsnote: 'Via PracticeMaster document management add-on',
        trek: 'no', lexring: 'no',
      },
      {
        key: 'fFullTextSearch',
        soi: 'planned',
        tabs: 'partial', tabsnote: 'With PracticeMaster add-on only',
        trek: 'no', lexring: 'no',
      },
    ],
  },

  {
    id: 'security',
    icon: 'ri-shield-check-line',
    features: [
      {
        key: 'fSelfHosted',
        soi: 'yes', soinote: 'Full control — runs on your server, your jurisdiction',
        tabs: 'yes', tabsnote: 'Windows server deployment — traditionally on-premise',
        trek: 'no', treknote: 'SaaS only — Singapore servers',
        lexring: 'no', lexringnote: 'SaaS only — Thailand servers',
      },
      {
        key: 'fCloudSaas',
        soi: 'yes', soinote: 'Can be deployed on any cloud VPS',
        tabs: 'partial', tabsnote: 'TABS3 Cloud available but limited vs on-premise',
        trek: 'yes', lexring: 'yes',
      },
      {
        key: 'fDataJurisdiction',
        soi: 'yes', soinote: 'Self-hosted — your server, your country',
        tabs: 'yes', tabsnote: 'Self-hosted on-premise',
        trek: 'no', treknote: 'Singapore-hosted — data leaves Thailand',
        lexring: 'yes', lexringnote: 'Thailand-hosted servers',
      },
      { key: 'fRbac', soi: 'yes', tabs: 'yes', trek: 'yes', lexring: 'yes' },
      {
        key: 'fAuditTrail',
        soi: 'yes', soinote: 'All agent actions logged with timestamps',
        tabs: 'yes', tabsnote: 'Security event log',
        trek: 'partial', treknote: 'Login events only',
        lexring: 'partial', lexringnote: 'Basic activity log — no agent action detail',
      },
      {
        key: 'fCustomDomain',
        soi: 'yes', soinote: 'Your domain, your server',
        tabs: 'yes', tabsnote: 'Self-hosted = your domain',
        trek: 'partial', treknote: 'Subdomain on legaltrek.com only',
        lexring: 'partial', lexringnote: 'Subdomain on lexring.th only',
      },
      {
        key: 'fRestApi',
        soi: 'yes', soinote: 'Every operation available — clients, matters, billing, email, agent, documents',
        tabs: 'partial', tabsnote: 'Limited API for PracticeMaster integration only',
        trek: 'partial', treknote: 'Export API only',
        lexring: 'partial', lexringnote: 'Limited integration API',
      },
      {
        key: 'fOpenCodebase',
        soi: 'yes', soinote: 'You own the code and the data',
        tabs: 'no', tabsnote: 'Proprietary Windows software',
        trek: 'no', treknote: 'Proprietary SaaS — limited data export',
        lexring: 'no', lexringnote: 'Proprietary SaaS',
      },
      {
        key: 'fMobileApp',
        soi: 'yes', soinote: 'React Native — live',
        tabs: 'partial', tabsnote: 'Mobile-responsive web for TABS3 Cloud only',
        trek: 'partial', treknote: 'Mobile-responsive web',
        lexring: 'partial', lexringnote: 'Mobile-responsive web',
      },
      {
        key: 'fMultiLangUi',
        soi: 'yes', soinote: 'Language switcher in nav — EN / ภาษาไทย',
        tabs: 'no', tabsnote: 'English only',
        trek: 'yes', treknote: 'Thai primary, English secondary',
        lexring: 'partial', lexringnote: 'Thai only — no English UI',
      },
      {
        key: 'fFieldLevelEncryption',
        soi: 'yes', soinote: 'AES-256-GCM on every PII field — names, contact details, passport/visa numbers, email addresses, subjects, and bodies. Random IV per field per save. A compromised database is unreadable without the key.',
        tabs: 'no', tabsnote: 'OS-level disk encryption only — MongoDB data readable by anyone with DB access',
        trek: 'no', treknote: 'No field-level encryption — SaaS DB access controlled by vendor',
        lexring: 'no', lexringnote: 'No field-level encryption — SaaS DB access controlled by vendor',
      },
      {
        key: 'fSearchOnEncrypted',
        soi: 'yes', soinote: 'HMAC-SHA256 keyword token index — search, conflict checks, and email association all query hash tokens, not plaintext',
        tabs: 'no', trek: 'no', lexring: 'no',
      },
      {
        key: 'fKeysSeparateFromData',
        soi: 'yes', soinote: 'Keys in environment / KMS — never stored in the database alongside the data they protect',
        tabs: 'no', trek: 'no', lexring: 'no',
      },
    ],
  },

  {
    id: 'pricing',
    icon: 'ri-price-tag-3-line',
    features: [
      {
        key: 'fPricingModel',
        soi: 'yes', soinote: 'Flat monthly or annual — firm-wide licence, no per-seat fees. Solo ฿2,350/mo (฿1,990 annual) · Firm ฿4,990/mo (฿3,990 annual) · Complete ฿7,990/mo (฿5,990 annual)',
        tabs: 'no', tabsnote: 'Per-seat + per-module licensing. Every module (Billing, Trust, GL, PracticeMaster) licensed separately per user',
        trek: 'no', treknote: 'Per-seat monthly — ฿1,500–3,000/user/month depending on plan',
        lexring: 'no', lexringnote: 'Per-seat monthly — ฿1,800–2,500/user/month',
      },
      {
        key: 'fSoloEntryPrice',
        soi: 'yes', soinote: '฿2,350/month or ฿1,990/month billed annually — full practice management, billing, filing cabinet, encryption',
        tabs: 'no', tabsnote: '$89/user/month cloud (~฿3,200) — billing + financials only. Add PracticeMaster: $124/user/month (~฿4,465)',
        trek: 'no', treknote: '฿1,500–3,000/month — basic matter + time tracking. No AI, no email, no encryption',
        lexring: 'no', lexringnote: '฿1,800–2,500/month — matter tracking + billing. No AI, no email integration, no encryption',
      },
      {
        key: 'fThreeAttorneyCost',
        soi: 'yes', soinote: '฿4,990/month or ฿3,990/month billed annually — same price regardless of headcount up to 5 seats',
        tabs: 'no', tabsnote: '$267/month cloud (~฿9,600) — billing only. Full suite with PracticeMaster: $372/month (~฿13,400)',
        trek: 'no', treknote: '฿4,500–9,000/month (3 × ฿1,500–3,000 per seat)',
        lexring: 'no', lexringnote: '฿5,400–7,500/month (3 × ฿1,800–2,500 per seat)',
      },
      {
        key: 'fFiveAttorneyCost',
        soi: 'yes', soinote: '฿7,990/month or ฿5,990/month billed annually — unlimited seats, still the same ceiling',
        tabs: 'no', tabsnote: '$445/month cloud (~฿16,000) — billing only. Full suite: $620/month (~฿22,300)',
        trek: 'no', treknote: '฿7,500–15,000/month (5 × ฿1,500–3,000 per seat)',
        lexring: 'no', lexringnote: '฿9,000–12,500/month (5 × ฿1,800–2,500 per seat)',
      },
      {
        key: 'fPerSeatFees',
        soi: 'no', soinote: 'Add staff freely — no extra charge',
        tabs: 'yes', tabsnote: 'Each module (Practice, Billing, Trust, GL) licensed per user — costs multiply with headcount',
        trek: 'yes', treknote: '฿1,500–3,000 / user / month — costs multiply with headcount',
        lexring: 'yes', lexringnote: '฿1,800–2,500 / user / month — costs multiply with headcount',
      },
      {
        key: 'fAiIncluded',
        soi: 'yes', soinote: 'AI classification in Firm tier (฿4,990/mo or ฿3,990 annual). All 10 agents in Complete (฿7,990/mo or ฿5,990 annual). No add-on cost',
        tabs: 'no', tabsnote: 'No AI offering at any price point',
        trek: 'no', treknote: 'No AI offering at any price point',
        lexring: 'no', lexringnote: 'No AI offering at any price point',
      },
      {
        key: 'fSetupFee',
        soi: 'no', soinote: 'No setup fee',
        tabs: 'yes', tabsnote: 'Reseller installation + configuration fees — typically $500–2,000+ depending on firm size',
        trek: 'yes', treknote: '฿15,000–30,000 one-time setup fee',
        lexring: 'yes', lexringnote: '฿10,000–20,000 one-time setup fee',
      },
      {
        key: 'fAnnualContract',
        soi: 'no', soinote: 'Month-to-month — cancel any time',
        tabs: 'yes', tabsnote: 'Annual licence renewal required',
        trek: 'yes', treknote: 'Annual contract standard',
        lexring: 'yes', lexringnote: 'Annual contract standard',
      },
      {
        key: 'fDataMigration',
        soi: 'yes', soinote: 'Included — migration tab built into platform',
        tabs: 'partial', tabsnote: 'Reseller-dependent — extra cost',
        trek: 'partial', treknote: 'Import tool — manual mapping required',
        lexring: 'partial', lexringnote: 'Manual import — extra cost',
      },
      {
        key: 'fVendorLockIn',
        soi: 'no', soinote: 'Open code + your server + your data — zero lock-in',
        tabs: 'yes', tabsnote: 'Proprietary format; migration requires TABS-certified reseller',
        trek: 'yes', treknote: 'Proprietary DB; limited export formats',
        lexring: 'yes', lexringnote: 'Proprietary SaaS; limited export',
      },
      {
        key: 'fLocalThaiSupport',
        soi: 'yes', soinote: 'Built for this firm — direct',
        tabs: 'no', tabsnote: 'US-based support only; no Thai reseller network',
        trek: 'yes', treknote: 'Thai-language support team',
        lexring: 'yes', lexringnote: 'Thai-language support team',
      },
    ],
  },
]

// ── Support badge ─────────────────────────────────────────────────────────────

function Badge({ status, note }: { status: Support; note?: string }) {
  const t = useT()
  const cfg: Record<Support, { icon: string; label: string; color: string; bg: string }> = {
    yes:     { icon: 'ri-checkbox-circle-fill',      label: t.compare.badgeYes,     color: '#0D9394', bg: 'rgba(13,147,148,0.1)' },
    partial: { icon: 'ri-indeterminate-circle-fill', label: t.compare.badgePartial, color: '#FF9F43', bg: 'rgba(255,159,67,0.1)' },
    no:      { icon: 'ri-close-circle-fill',         label: t.compare.badgeNo,      color: '#a0a0a0', bg: 'rgba(160,160,160,0.08)' },
    planned: { icon: 'ri-time-line',                 label: t.compare.badgePlanned, color: '#696CFF', bg: 'rgba(105,108,255,0.1)' },
  }
  const { icon, label, color, bg } = cfg[status]
  const el = (
    <Box sx={{
      display: 'inline-flex', alignItems: 'center', gap: 0.75,
      bgcolor: bg, borderRadius: 1.5, px: 1.25, py: 0.5,
    }}>
      <i className={icon} style={{ color, fontSize: '1rem' }} />
      <Typography variant='caption' sx={{ color, fontWeight: 700, fontSize: '0.78rem' }}>
        {label}
      </Typography>
    </Box>
  )
  if (note) return <Tooltip title={note} placement='top' arrow><span style={{ cursor: 'help' }}>{el}</span></Tooltip>
  return el
}

// ── Score summary bar ─────────────────────────────────────────────────────────

function ScoreBar({ features }: { features: Feature[] }) {
  const score = (vals: Support[]) => {
    const pts = vals.reduce((s, v) => s + (v === 'yes' ? 2 : v === 'planned' ? 1 : v === 'partial' ? 1 : 0), 0)
    return Math.round((pts / (vals.length * 2)) * 100)
  }
  const soi     = score(features.map(f => f.soi))
  const tabs    = score(features.map(f => f.tabs))
  const trek    = score(features.map(f => f.trek))
  const lexring = score(features.map(f => f.lexring))

  return (
    <Box sx={{ display: 'flex', gap: 3, px: 3, py: 1.5, bgcolor: 'action.hover', borderBottom: '1px solid', borderColor: 'divider' }}>
      {[
        { label: 'Soi96 Legal', pct: soi,     color: '#0D9394' },
        { label: 'TABS3',       pct: tabs,    color: '#8592A3' },
        { label: 'LegalTrek',   pct: trek,    color: '#8592A3' },
        { label: 'LexRing',     pct: lexring, color: '#8592A3' },
      ].map(({ label, pct, color }) => (
        <Box key={label} sx={{ display: 'flex', alignItems: 'center', gap: 1.5, flex: 1 }}>
          <Typography variant='caption' sx={{ fontWeight: 700, color, whiteSpace: 'nowrap', minWidth: 90 }}>
            {label}
          </Typography>
          <Box sx={{ flex: 1, bgcolor: 'divider', borderRadius: 4, height: 6, overflow: 'hidden' }}>
            <Box sx={{ width: `${pct}%`, bgcolor: color, height: '100%', borderRadius: 4, transition: 'width 0.4s ease' }} />
          </Box>
          <Typography variant='caption' sx={{ fontWeight: 700, color, minWidth: 32, textAlign: 'right' }}>
            {pct}%
          </Typography>
        </Box>
      ))}
    </Box>
  )
}

// ── Main ──────────────────────────────────────────────────────────────────────

export default function ComparisonView() {
  const t = useT()
  const [tab, setTab] = useState(0)
  const [billing, setBilling] = useState<'monthly' | 'annual'>('monthly')
  const cat = CATEGORIES[tab]

  const catLabel: Record<string, string> = {
    practice: t.compare.catPractice,
    ai:       t.compare.catAi,
    comms:    t.compare.catComms,
    billing:  t.compare.catBilling,
    documents:t.compare.catDocuments,
    security: t.compare.catSecurity,
    pricing:  t.compare.catPricing,
  }

  const fLabel = (key: string) => (t.compare as Record<string, string>)[key] ?? key

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>

      {/* Hero */}
      <Box sx={{ background: 'linear-gradient(135deg, #0D9394 0%, #096B6C 100%)', borderRadius: 3, p: 4, color: '#fff' }}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5, mb: 1 }}>
          <i className='ri-bar-chart-horizontal-line' style={{ fontSize: '1.6rem' }} />
          <Typography variant='h4' sx={{ fontWeight: 700, color: '#fff' }}>{t.compare.title}</Typography>
        </Box>
        <Typography variant='body1' sx={{ color: 'rgba(255,255,255,0.85)', maxWidth: 640, mb: 2.5 }}>
          {t.compare.subtitle}
        </Typography>
        <Box sx={{ display: 'flex', gap: 2 }}>
          {[
            { label: 'Soi96 Legal', sub: t.compare.thisPlatform, solid: true },
            { label: 'TABS3',       sub: t.compare.usBillingPm,  solid: false },
            { label: 'LegalTrek',   sub: t.compare.thaiSaas,     solid: false },
            { label: 'LexRing',     sub: t.compare.thaiSaas,     solid: false },
          ].map(b => (
            <Box key={b.label} sx={{
              border: `1px solid ${b.solid ? 'rgba(255,255,255,0.6)' : 'rgba(255,255,255,0.25)'}`,
              bgcolor: b.solid ? 'rgba(255,255,255,0.2)' : 'transparent',
              borderRadius: 2, px: 2.5, py: 1,
            }}>
              <Typography variant='body2' sx={{ color: b.solid ? '#fff' : 'rgba(255,255,255,0.7)', fontWeight: 700, lineHeight: 1.3 }}>
                {b.label}
              </Typography>
              <Typography variant='caption' sx={{ color: b.solid ? 'rgba(255,255,255,0.8)' : 'rgba(255,255,255,0.45)' }}>
                {b.sub}
              </Typography>
            </Box>
          ))}
        </Box>
      </Box>

      {/* ── Pricing plans ── */}
      <Box>
        <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 0.5, flexWrap: 'wrap', gap: 1 }}>
          <Typography variant='h6' sx={{ fontWeight: 700 }}>{t.compare.pricingTitle}</Typography>
          {/* Billing toggle */}
          <Box sx={{ display: 'flex', bgcolor: 'action.hover', borderRadius: 2, p: 0.5, gap: 0.5 }}>
            {(['monthly', 'annual'] as const).map(opt => (
              <Box key={opt} onClick={() => setBilling(opt)} sx={{
                px: 2, py: 0.5, borderRadius: 1.5, cursor: 'pointer', transition: 'all 0.15s',
                bgcolor: billing === opt ? (opt === 'annual' ? '#0D9394' : 'background.paper') : 'transparent',
                boxShadow: billing === opt ? 1 : 0,
              }}>
                <Typography variant='caption' sx={{
                  fontWeight: 700,
                  color: billing === opt ? (opt === 'annual' ? '#fff' : 'text.primary') : 'text.secondary',
                }}>
                  {opt === 'monthly' ? 'Monthly' : 'Annual'}
                  {opt === 'annual' && <span style={{ marginLeft: 6, fontSize: '0.65rem', opacity: 0.9 }}>save up to 25%</span>}
                </Typography>
              </Box>
            ))}
          </Box>
        </Box>
        <Typography variant='body2' color='text.secondary' sx={{ mb: 2 }}>
          {billing === 'annual' ? 'Billed annually — cancel any time.' : t.compare.pricingSubtitle}
        </Typography>
        <Box sx={{ display: 'grid', gridTemplateColumns: { xs: '1fr', sm: 'repeat(3, 1fr)' }, gap: 2 }}>
          {SOI_PLAN_KEYS.map(plan => {
            const name     = (t.compare as Record<string, string>)[plan.nameKey]
            const seats    = (t.compare as Record<string, string>)[plan.seatKey]
            const price    = billing === 'annual' ? plan.annualPrice : plan.monthlyPrice
            const hasDiscount = billing === 'annual' && plan.savePct > 0
            return (
              <Card key={plan.nameKey} sx={{
                border: plan.highlight ? '2px solid #0D9394' : '1px solid',
                borderColor: plan.highlight ? '#0D9394' : 'divider',
                position: 'relative', overflow: 'visible',
              }}>
                {plan.highlight && (
                  <Box sx={{
                    position: 'absolute', top: -12, left: '50%', transform: 'translateX(-50%)',
                    bgcolor: '#0D9394', color: '#fff', borderRadius: 10, px: 1.5, py: 0.25,
                    fontSize: '0.7rem', fontWeight: 700, whiteSpace: 'nowrap',
                  }}>
                    {t.compare.mostPopular}
                  </Box>
                )}
                <Box sx={{ p: 2.5 }}>
                  <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 0.25 }}>
                    <Typography variant='overline' sx={{ color: 'text.disabled', fontWeight: 700, letterSpacing: 1 }}>
                      {name}
                    </Typography>
                    {hasDiscount && (
                      <Chip label={`Save ${plan.savePct}%`} size='small' sx={{
                        bgcolor: 'rgba(13,147,148,0.12)', color: '#0D9394',
                        fontWeight: 700, fontSize: '0.68rem', height: 20,
                      }} />
                    )}
                  </Box>
                  {hasDiscount && (
                    <Typography variant='caption' sx={{ color: 'text.disabled', textDecoration: 'line-through', display: 'block', lineHeight: 1.2 }}>
                      {plan.monthlyPrice}/mo
                    </Typography>
                  )}
                  <Box sx={{ display: 'flex', alignItems: 'baseline', gap: 0.5, mt: 0.25, mb: 0.25 }}>
                    <Typography sx={{ fontSize: '1.8rem', fontWeight: 800, color: plan.highlight ? '#0D9394' : 'text.primary', lineHeight: 1 }}>
                      {price}
                    </Typography>
                    <Typography variant='caption' color='text.secondary'>{t.compare.perMonth}</Typography>
                  </Box>
                  <Typography variant='caption' color='text.secondary' sx={{ display: 'block', mb: 2 }}>
                    {seats}
                  </Typography>
                  <Divider sx={{ mb: 1.5 }} />
                  {plan.featureKeys.map(k => (
                    <Box key={k} sx={{ display: 'flex', alignItems: 'flex-start', gap: 1, mb: 0.75 }}>
                      <i className='ri-checkbox-circle-fill' style={{ color: '#0D9394', fontSize: '1rem', flexShrink: 0, marginTop: 1 }} />
                      <Typography variant='caption' sx={{ lineHeight: 1.4 }}>{(t.compare as Record<string, string>)[k]}</Typography>
                    </Box>
                  ))}
                  {plan.notIncludedKeys.map(k => (
                    <Box key={k} sx={{ display: 'flex', alignItems: 'flex-start', gap: 1, mb: 0.75 }}>
                      <i className='ri-close-circle-line' style={{ color: '#CBD5E1', fontSize: '1rem', flexShrink: 0, marginTop: 1 }} />
                      <Typography variant='caption' color='text.disabled' sx={{ lineHeight: 1.4 }}>{(t.compare as Record<string, string>)[k]}</Typography>
                    </Box>
                  ))}
                </Box>
              </Card>
            )
          })}
        </Box>
      </Box>

      {/* ── Cost comparison ── */}
      <Box>
        <Typography variant='h6' sx={{ fontWeight: 700, mb: 0.5 }}>{t.compare.costTitle}</Typography>
        <Typography variant='body2' color='text.secondary' sx={{ mb: 2 }}>
          {t.compare.costSubtitle}
        </Typography>
        <Card>
          <Box sx={{
            display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr 1fr',
            px: 2.5, py: 1.5, bgcolor: 'action.hover',
            borderBottom: '1px solid', borderColor: 'divider',
          }}>
            {[t.compare.colFirmSize, 'Soi96 Legal', 'TABS3 Cloud', 'LegalTrek', 'LexRing'].map((h, i) => (
              <Typography key={h} variant='caption' sx={{
                fontWeight: 700, color: i === 1 ? '#0D9394' : 'text.secondary',
                textAlign: i > 0 ? 'center' : 'left',
              }}>{h}</Typography>
            ))}
          </Box>
          {COST_SCENARIOS.map((row, i) => (
            <Box key={row.labelKey}>
              <Box sx={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr 1fr', px: 2.5, py: 1.75, alignItems: 'center' }}>
                <Typography variant='body2' sx={{ fontWeight: 600 }}>{(t.compare as Record<string, string>)[row.labelKey]}</Typography>
                <Box sx={{ textAlign: 'center', bgcolor: 'rgba(13,147,148,0.06)', borderRadius: 1, py: 0.5, mx: 0.5 }}>
                  <Typography variant='body2' sx={{ fontWeight: 700, color: '#0D9394' }}>{row.soi}</Typography>
                </Box>
                <Box sx={{ textAlign: 'center' }}>
                  <Typography variant='body2' color='text.secondary'>{row.tabs}</Typography>
                </Box>
                <Box sx={{ textAlign: 'center' }}>
                  <Typography variant='body2' color='text.secondary'>{row.trek}</Typography>
                </Box>
                <Box sx={{ textAlign: 'center' }}>
                  <Typography variant='body2' color='text.secondary'>{row.lexring}</Typography>
                </Box>
              </Box>
              {i < COST_SCENARIOS.length - 1 && <Divider />}
            </Box>
          ))}
          <Box sx={{ px: 2.5, py: 1.25, bgcolor: 'action.hover', borderTop: '1px solid', borderColor: 'divider' }}>
            <Typography variant='caption' color='text.disabled'>
              {t.compare.costFootnote}
            </Typography>
          </Box>
        </Card>
      </Box>

      {/* Tabs */}
      <Card>
        <Tabs
          value={tab} onChange={(_, v) => setTab(v)}
          variant='scrollable' scrollButtons='auto'
          sx={{ borderBottom: '1px solid', borderColor: 'divider', px: 2, '& .MuiTab-root': { minHeight: 52, fontWeight: 600, fontSize: '0.875rem' } }}
        >
          {CATEGORIES.map((c, i) => (
            <Tab key={c.id} label={catLabel[c.id] ?? c.id} icon={<i className={c.icon} style={{ fontSize: '1rem' }} />} iconPosition='start' value={i} />
          ))}
        </Tabs>

        {/* Score bar */}
        <ScoreBar features={cat.features} />

        {/* Column headers */}
        <Box sx={{
          display: 'grid', gridTemplateColumns: '1fr 140px 140px 140px 140px',
          px: 3, py: 1.75, bgcolor: 'background.default',
          borderBottom: '1px solid', borderColor: 'divider',
        }}>
          <Box />
          {[
            { label: 'Soi96 Legal', sub: t.compare.thisPlatform, highlight: true },
            { label: 'TABS3',       sub: t.compare.usBillingPm,  highlight: false },
            { label: 'LegalTrek',   sub: t.compare.thaiSaas,     highlight: false },
            { label: 'LexRing',     sub: t.compare.thaiSaas,     highlight: false },
          ].map(col => (
            <Box key={col.label} sx={{
              display: 'flex', flexDirection: 'column', alignItems: 'center',
              bgcolor: col.highlight ? 'rgba(13,147,148,0.06)' : 'transparent',
              border: col.highlight ? '1px solid rgba(13,147,148,0.2)' : '1px solid transparent',
              borderRadius: 2, mx: 0.5, py: 1, px: 1,
            }}>
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.6, mb: 0.25 }}>
                <Box sx={{ width: 7, height: 7, borderRadius: '50%', bgcolor: col.highlight ? '#0D9394' : '#a0a0a0' }} />
                <Typography variant='body2' sx={{ fontWeight: 800, color: col.highlight ? '#0D9394' : 'text.secondary', fontSize: '0.82rem' }}>
                  {col.label}
                </Typography>
              </Box>
              <Chip label={col.sub} size='small' sx={{
                bgcolor: col.highlight ? 'rgba(13,147,148,0.12)' : 'rgba(160,160,160,0.1)',
                color: col.highlight ? '#0D9394' : 'text.secondary',
                fontWeight: 700, fontSize: '0.68rem', height: 18,
              }} />
            </Box>
          ))}
        </Box>

        {/* Feature rows */}
        <CardContent sx={{ p: 0 }}>
          {cat.features.map((f, i) => (
            <Box key={f.key}>
              <Box sx={{
                display: 'grid', gridTemplateColumns: '1fr 140px 140px 140px 140px',
                px: 3, py: 1.75, alignItems: 'center',
                '&:hover': { bgcolor: 'action.hover' }, transition: 'background 0.15s',
              }}>
                <Box>
                  <Typography variant='body2' sx={{ fontWeight: 500 }}>{fLabel(f.key)}</Typography>
                  {f.note && <Typography variant='caption' color='text.secondary'>{f.note}</Typography>}
                </Box>
                <Box sx={{ display: 'flex', justifyContent: 'center', bgcolor: 'rgba(13,147,148,0.03)', mx: 0.5, borderRadius: 1, py: 0.5 }}>
                  <Badge status={f.soi} note={f.soinote} />
                </Box>
                <Box sx={{ display: 'flex', justifyContent: 'center', mx: 0.5, py: 0.5 }}>
                  <Badge status={f.tabs} note={f.tabsnote} />
                </Box>
                <Box sx={{ display: 'flex', justifyContent: 'center', mx: 0.5, py: 0.5 }}>
                  <Badge status={f.trek} note={f.treknote} />
                </Box>
                <Box sx={{ display: 'flex', justifyContent: 'center', mx: 0.5, py: 0.5 }}>
                  <Badge status={f.lexring} note={f.lexringnote} />
                </Box>
              </Box>
              {i < cat.features.length - 1 && <Divider />}
            </Box>
          ))}
        </CardContent>
      </Card>

      {/* Legend */}
      <Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap', px: 0.5, pb: 1 }}>
        {([
          ['yes',     t.compare.legendYes],
          ['partial', t.compare.legendPartial],
          ['planned', t.compare.legendPlanned],
          ['no',      t.compare.legendNo],
        ] as [Support, string][]).map(([status, desc]) => (
          <Box key={status} sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <Badge status={status} />
            <Typography variant='caption' color='text.secondary'>{desc}</Typography>
          </Box>
        ))}
        <Typography variant='caption' color='text.secondary' sx={{ ml: 'auto', fontStyle: 'italic' }}>
          {t.compare.hoverHint}
        </Typography>
      </Box>

    </Box>
  )
}
