import {
  ArrowRight,
  BookOpen,
  Brain,
  Check,
  ChevronDown,
  CircleCheckBig,
  Code2,
  FileCheck2,
  FileCode2,
  FolderOpen,
  GitBranch,
  History,
  LayoutTemplate,
  PanelsTopLeft,
  Quote,
  ShieldCheck,
  SquareTerminal,
  Users,
  Zap,
  type LucideIcon,
} from 'lucide-react';
import React from 'react';
import compareContent from './compare-content.json';
import migrationContent from './migration-content.json';

export type PublicPricingPlanId = 'free' | 'lifetime' | 'monthly';

export type PublicPricingPlan = {
  id: PublicPricingPlanId;
  name: string;
  price: string;
  supportingLine: string;
  badge?: string;
  features: readonly string[];
  cta: string;
  href: 'projects' | 'lifetime-shop' | 'monthly-shop';
  support: 'Community' | 'Priority';
};

const LEARNITIVE_PRO_FEATURES = [
  'Unlimited projects',
  'Everything in Free',
  'BYOK AI providers',
  'Full collaboration hosting',
  'Premium AI research tools',
  'Ollama local models',
  'AI Review',
  'Paper Memory',
  'Project Terminal',
  'Pro Templates',
  'Version control',
  'Clean premium PDF export',
  'Priority support',
] as const;

export const LEARNITIVE_PRICING_PLANS: readonly PublicPricingPlan[] = [
  {
    id: 'free',
    name: 'Free',
    price: '$0 forever',
    supportingLine: 'Up to 5 projects',
    features: [
      'Up to 5 projects',
      'Markdown and visual writing',
      'LaTeX and PDF workflow',
      'Local-first project storage',
      'Local AI',
      'Join invited collaborations',
      'Community support',
    ],
    cta: 'Start free',
    href: 'projects',
    support: 'Community',
  },
  {
    id: 'lifetime',
    name: 'Pro Lifetime',
    price: '$29 one-time',
    supportingLine: 'Pay once. Keep Pro.',
    badge: 'Most Popular',
    features: LEARNITIVE_PRO_FEATURES,
    cta: 'Get Pro Lifetime',
    href: 'lifetime-shop',
    support: 'Priority',
  },
  {
    id: 'monthly',
    name: 'Pro Monthly',
    price: '$5 / month',
    supportingLine: 'Full Pro access, billed monthly.',
    features: LEARNITIVE_PRO_FEATURES,
    cta: 'Get Pro Monthly',
    href: 'monthly-shop',
    support: 'Priority',
  },
] as const;

export const LEARNITIVE_PLAN_COMPARISON = [
  ['Projects', 'Up to 5', 'Unlimited', 'Unlimited'],
  ['Markdown and visual writing', '✓', '✓', '✓'],
  ['LaTeX and PDF workflow', '✓', '✓', '✓'],
  ['Local-first project storage', '✓', '✓', '✓'],
  ['Local AI', '✓', '✓', '✓'],
  ['Join invited collaborations', '✓', '✓', '✓'],
  ['BYOK AI providers', '—', '✓', '✓'],
  ['Full collaboration hosting', '—', '✓', '✓'],
  ['Premium AI research tools', '—', '✓', '✓'],
  ['Ollama local models', '—', '✓', '✓'],
  ['AI Review', '—', '✓', '✓'],
  ['Paper Memory', '—', '✓', '✓'],
  ['Project Terminal', '—', '✓', '✓'],
  ['Pro Templates', '—', '✓', '✓'],
  ['Version control', '—', '✓', '✓'],
  ['Clean premium PDF export', '—', '✓', '✓'],
  ['Support', 'Community', 'Priority', 'Priority'],
  ['Price', '$0', '$29 one-time', '$5/month'],
] as const;

export const HOME_FAQ = [
  ['What is Learnitive?', 'Learnitive is a local-first learning, research and writing workspace. Create Markdown and LaTeX projects, organise sources and citations, work with AI, study course material and turn research into finished documents from one workspace.'],
  ['Is Learnitive free?', 'Yes. Learnitive includes a Free plan for core writing, research and local-first workflows. Free includes up to {{LEARNITIVE_FREE_PLAN_LIMIT}} projects; Pro expands project limits and unlocks premium capabilities such as BYOK AI and full collaboration hosting.'],
  ['Does Learnitive support Markdown and LaTeX?', 'Yes. Markdown is the default for general writing, notes, articles and books. LaTeX remains first-class for research papers, theses, mathematics, bibliography workflows and professional PDF output.'],
  ['How is Learnitive different from Overleaf?', 'Overleaf is primarily a collaborative LaTeX platform. Learnitive combines LaTeX with Markdown, local-first projects, research workflows, AI, learning tools and optional advanced project tooling.'],
  ['Where are my projects stored?', 'Projects can remain in browser storage or in a folder you explicitly link where supported. Signing in does not automatically make Learnitive’s SaaS database the source of truth for your document contents.'],
  ['Can I import an Overleaf or existing project?', 'Yes. ZIP and Git import capabilities remain available. An exported Overleaf project can be imported as a LaTeX project.'],
  ['Does Learnitive include AI?', 'Yes. Learnitive supports Local AI on Free. Pro adds BYOK AI providers, Ollama local models, AI Review, Paper Memory and premium AI research tools.'],
  ['Does Learnitive include a terminal?', 'Yes. Advanced projects can use an integrated Ubuntu project terminal for Git, LaTeX, Python and other project tooling. It is available when needed but is not required for ordinary writing or learning.'],
  ['Can I collaborate?', 'Yes. Learnitive supports shared projects. Joining an invited collaboration is available on Free, while starting and hosting collaborations is a Pro capability.'],
  ['Can I learn inside Learnitive?', 'Yes. Learnitive includes courses and structured learning content alongside projects, writing and research.'],
  ['Can I use Learnitive without AI?', 'Yes. Markdown, LaTeX, projects, courses and the core editor work without AI. AI remains optional assistance.'],
  ['What does the $29 lifetime licence include?', 'The launch Learnitive Pro Lifetime licence is a one-time $29 product entitlement. Third-party AI providers may charge separately when you use your own API key.'],
] as const;

export const PRICING_FAQ = [
  ['What stays free?', 'Free includes up to {{LEARNITIVE_FREE_PLAN_LIMIT}} projects, Markdown and visual writing, LaTeX and PDF workflow, local-first project storage, Local AI, invited collaboration access and community support.'],
  ['What does Pro add?', 'Pro includes everything in Free and adds unlimited projects, BYOK AI providers, full collaboration hosting, premium AI research tools, Ollama local models, AI Review, Paper Memory, Project Terminal, Pro Templates, version control, clean premium PDF export and priority support.'],
  ['Can I choose Monthly instead of Lifetime?', 'Yes. Learnitive Pro Monthly is $5 per month and includes the same product features as Pro Lifetime. Pro Lifetime remains a $29 one-time licence.'],
  ['What happens when Monthly Pro expires?', 'The account returns to Free. Local project files remain local and are not deleted or locked.'],
  ['Does a lifetime licence mean unlimited third-party AI usage?', 'No. Your Learnitive product entitlement is lifetime, while third-party model costs, BYOK provider quotas and any abuse/resource protections remain governed separately.'],
] as const;

type PricingVariant = 'home' | 'full';

const DEFAULT_PUBLIC_FREE_PROJECT_LIMIT = 5;

function normalizedPublicFreeProjectLimit(value?: number): number {
  const parsed = Number(value);
  return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : DEFAULT_PUBLIC_FREE_PROJECT_LIMIT;
}

function freeProjectCopy(value: string, limit: number): string {
  return value
    .replaceAll('{{LEARNITIVE_FREE_PLAN_LIMIT}}', String(limit))
    .replace(/^Up to \d+ projects$/u, `Up to ${limit} projects`);
}

function PricingFeatureLabel({ feature }: { feature: string }) {
  const projectMatch = feature.match(/^Up to (\d+) projects$/u);
  if (projectMatch) return <>Up to <strong>{projectMatch[1]} projects</strong></>;
  if (feature === 'Unlimited projects') return <><strong>Unlimited</strong> projects</>;
  if (feature === 'Limited terminal persistence') return <><strong>Limited</strong> terminal persistence</>;
  if (feature === 'Join collaborations only') return <><strong>Join</strong> collaborations only</>;
  if (feature === 'Persistent terminal workspaces') return <><strong>Persistent</strong> terminal workspaces</>;
  if (feature === 'Public Internet access') return <>Public <strong>Internet</strong> access</>;
  if (feature === 'Interactive AI, Ollama and BYOK') return <>Interactive AI, <strong>Ollama</strong> and BYOK</>;
  if (feature === 'Scientific Tools and LaTeX') return <>Scientific Tools and <strong>LaTeX</strong></>;
  if (feature === 'Full collaboration') return <><strong>Full</strong> collaboration</>;
  if (feature === 'Priority support') return <><strong>Priority</strong> support</>;
  return <>{feature}</>;
}

function PricingFeatureName({ feature }: { feature: string }) {
  return feature === 'Interactive AI builder agent' ? <strong>{feature}</strong> : <>{feature}</>;
}

export function LearnitivePricingTable({
  variant,
  lifetimeShopUrl,
  monthlyShopUrl,
  freeProjectLimit,
}: {
  variant: PricingVariant;
  lifetimeShopUrl?: string;
  monthlyShopUrl?: string;
  freeProjectLimit?: number;
}) {
  const effectiveFreeProjectLimit = normalizedPublicFreeProjectLimit(freeProjectLimit);
  const pricingPlans = LEARNITIVE_PRICING_PLANS.map((plan) => plan.id === 'free'
    ? { ...plan, supportingLine: freeProjectCopy(plan.supportingLine, effectiveFreeProjectLimit), features: plan.features.map((feature) => freeProjectCopy(feature, effectiveFreeProjectLimit)) }
    : plan);
  const hrefForPlan = (plan: PublicPricingPlan) => {
    if (plan.href === 'projects') return '/projects';
    if (plan.href === 'lifetime-shop') return lifetimeShopUrl;
    return monthlyShopUrl;
  };
  const accessibleHeading = variant === 'home' ? 'interactive-pricing-home-title' : undefined;
  return (
    <section
      className={`interactive-page-container interactive-pricing-section interactive-pricing-section-${variant}`}
      aria-labelledby={accessibleHeading}
      aria-label={variant === 'full' ? 'Pricing plans' : undefined}
    >
      {variant === 'home' ? (
        <div className="interactive-section-heading interactive-pricing-heading">
          <span className="interactive-eyebrow">Pricing</span>
          <h2 id="interactive-pricing-home-title">Simple pricing. Keep control of your work.</h2>
          <p>Start free with the core Learnitive writing, research and local-first workflow. Upgrade to Pro for unlimited projects, BYOK AI, full collaboration features and premium exports.</p>
        </div>
      ) : null}
      <div className="interactive-pricing-cards">
        {pricingPlans.map((plan) => {
          const href = hrefForPlan(plan);
          return (
            <article className={`interactive-pricing-card${plan.id === 'lifetime' ? ' interactive-pricing-card-featured' : ''}`} key={plan.id} data-plan={plan.id}>
              <div className="interactive-pricing-card-head">
                <div>
                  <h3>{plan.name}</h3>
                  {plan.badge ? <span className="interactive-pricing-badge">{plan.badge}</span> : null}
                </div>
                <strong>{plan.price}</strong>
                <p>{plan.supportingLine}</p>
              </div>
              <ul>
                {plan.features.map((feature) => <li key={feature}><Check className="size-4" aria-hidden="true" /><span><PricingFeatureLabel feature={feature} /></span></li>)}
              </ul>
              {href ? (
                <a className={`interactive-button ${plan.id === 'lifetime' ? 'interactive-button-primary' : 'interactive-button-secondary'}`} href={href} rel={plan.href === 'projects' ? undefined : 'noreferrer'}>
                  {plan.cta}{plan.id === 'lifetime' ? <ArrowRight className="size-4" aria-hidden="true" /> : null}
                </a>
              ) : (
                <span className="interactive-button interactive-button-secondary is-disabled" aria-disabled="true" title={plan.id === 'monthly' ? 'Monthly Pro checkout is not configured on this deployment.' : 'Lifetime checkout is not configured on this deployment.'}>{plan.cta}</span>
              )}
            </article>
          );
        })}
      </div>
      <p className="interactive-muted interactive-pricing-auth-note">Sign-in is required for account-linked Pro features and collaboration. Starting a collaboration requires Pro; joining requires authenticated project access.</p>
      <p className="interactive-pricing-license-link">Already purchased Learnitive Pro? <a className="interactive-text-link" href="/apply">Apply your license <ArrowRight className="size-4" aria-hidden="true" /></a></p>
      {variant === 'home' ? <a className="interactive-text-link interactive-pricing-compare-link" href="/pricing">Compare plans <ArrowRight className="size-4" aria-hidden="true" /></a> : null}
    </section>
  );
}

function PricingMatrixValue({ value }: { value: string }) {
  if (value === 'no watermark') return <strong>no watermark</strong>;
  return <>{value}</>;
}

export function PricingComparisonTable({ freeProjectLimit }: { freeProjectLimit?: number }) {
  const effectiveFreeProjectLimit = normalizedPublicFreeProjectLimit(freeProjectLimit);
  const comparison = LEARNITIVE_PLAN_COMPARISON.map(([feature, free, lifetime, monthly]) => [feature, freeProjectCopy(free, effectiveFreeProjectLimit), lifetime, monthly] as const);
  return (
    <section className="interactive-page-container interactive-public-section" aria-labelledby="interactive-plan-comparison-title">
      <div className="interactive-section-heading">
        <span className="interactive-eyebrow">Compare plans</span>
        <h2 id="interactive-plan-comparison-title">Free, Lifetime and Monthly, side by side</h2>
      </div>
      <div className="interactive-table-scroll">
        <table className="interactive-pricing-matrix">
          <thead><tr><th scope="col">Feature</th><th scope="col">Free</th><th scope="col">Pro Lifetime</th><th scope="col">Pro Monthly</th></tr></thead>
          <tbody>{comparison.map(([feature, free, lifetime, monthly]) => <tr key={feature}><th scope="row"><PricingFeatureName feature={feature} /></th><td><PricingMatrixValue value={free} /></td><td><PricingMatrixValue value={lifetime} /></td><td><PricingMatrixValue value={monthly} /></td></tr>)}</tbody>
        </table>
      </div>
      <p className="interactive-muted interactive-pricing-auth-note">* Sign-in is required for account-linked Pro features and collaboration. Starting a collaboration requires Pro; joining requires authenticated project access.</p>
    </section>
  );
}

export function PublicFaq({ title, eyebrow = 'FAQ', items, freeProjectLimit }: { title: string; eyebrow?: string; items: readonly (readonly [string, string])[]; freeProjectLimit?: number }) {
  const effectiveFreeProjectLimit = normalizedPublicFreeProjectLimit(freeProjectLimit);
  return (
    <section className="interactive-page-container interactive-public-section interactive-faq-section" aria-labelledby={`faq-${title.replace(/\W+/gu, '-').toLowerCase()}`}>
      <div className="interactive-section-heading interactive-faq-heading"><span className="interactive-eyebrow">{eyebrow}</span><h2 id={`faq-${title.replace(/\W+/gu, '-').toLowerCase()}`}>{title}</h2></div>
      <div className="interactive-faq-list">{items.map(([question, answer]) => <details key={question}><summary><span>{question}</span><ChevronDown className="size-4" aria-hidden="true" /></summary><p>{freeProjectCopy(answer, effectiveFreeProjectLimit)}</p></details>)}</div>
    </section>
  );
}

export function PublicFinalCta({
  heading = 'Ready to write with Learnitive?',
  copy = 'Start with your own project or choose a template.',
  primaryLabel = 'Open Projects',
  primaryHref = '/projects',
  secondaryLabel = 'Browse Templates',
  secondaryHref = '/templates',
}: {
  heading?: string;
  copy?: string;
  primaryLabel?: string;
  primaryHref?: string;
  secondaryLabel?: string;
  secondaryHref?: string;
}) {
  return <section className="interactive-page-container interactive-final-cta"><h2>{heading}</h2><p>{copy}</p><div className="interactive-hero-actions"><a className="interactive-button interactive-button-primary" href={primaryHref}>{primaryLabel}<ArrowRight className="size-4" aria-hidden="true" /></a><a className="interactive-button interactive-button-secondary" href={secondaryHref}>{secondaryLabel}</a></div></section>;
}

type PowerFeature = { title: string; copy: string; icon: LucideIcon };

const POWER_FEATURES: readonly PowerFeature[] = [
  { title: 'Markdown + Visual Writing', copy: 'Write in a visual, document-focused experience while keeping portable Markdown source available when you want it.', icon: PanelsTopLeft },
  { title: 'LaTeX + PDF', copy: 'Create academic and technical documents with equations, bibliography workflows, compilation and PDF preview.', icon: FileCheck2 },
  { title: 'Research Context', copy: 'Keep citations, bibliography files, Paper Memory and project material close to the document you are writing.', icon: BookOpen },
  { title: 'AI Writer', copy: 'Draft, rewrite and summarise with project-aware assistance instead of moving text between disconnected tools.', icon: Brain },
  { title: 'Local AI + BYOK', copy: 'Use local models or explicitly connect supported cloud AI providers with your own key on Pro.', icon: ShieldCheck },
  { title: 'Local First', copy: 'Keep ordinary project files under your control using browser storage and supported project-folder workflows.', icon: FolderOpen },
] as const;

export function HomePowerFeatures() {
  return (
    <section className="interactive-why-section interactive-power-features-section" aria-labelledby="interactive-power-features-title" data-home-section="power-features">
      <div className="interactive-why-heading">
        <span className="interactive-eyebrow">A complete writing workspace</span>
        <h2 id="interactive-power-features-title">Everything you need to take an idea to a finished document.</h2>
        <p>Draft, research, structure and publish from one local-first workspace without giving up portable source files.</p>
      </div>
      <div className="interactive-why-grid interactive-power-features-grid">
        {POWER_FEATURES.map((feature, index) => {
          const Icon = feature.icon;
          return (
            <article className="interactive-why-card interactive-power-feature-card" key={feature.title} style={{ '--learnitive-why-delay': `${index * 45}ms` } as React.CSSProperties}>
              <span className="interactive-why-card-pin" aria-hidden="true"><Icon className="size-5" /></span>
              <h3>{feature.title}</h3>
              <p>{feature.copy}</p>
            </article>
          );
        })}
      </div>
    </section>
  );
}

const PRODUCT_COMPARISON = [
  ['LaTeX source editing', '✓', '✓'],
  ['Visual + source workflow', '✓', '✓'],
  ['PDF preview', '✓', '✓'],
  ['Markdown projects', '✓', '—'],
  ['Browser/local-first projects', '✓', '—'],
  ['Linked local folders', '✓', '—'],
  ['Offline-capable local workflows', '✓', '—'],
  ['Real-time collaboration', '✓', '✓'],
  ['Citations + bibliography', '✓', '✓'],
  ['Local AI / Ollama', '✓', '—'],
  ['BYOK AI', 'Pro', '—'],
  ['Paper Memory', '✓', '—'],
  ['Research evidence workflow', '✓', '—'],
  ['Integrated project terminal', '✓', '—'],
  ['Python / R / scientific tooling', '✓', '—'],
  ['Git workflows', '✓', 'Plan-dependent'],
  ['Learning/course workspace', '✓', '—'],
] as const;

type HomeComparisonValue = (typeof PRODUCT_COMPARISON)[number][1] | (typeof PRODUCT_COMPARISON)[number][2];

function ComparisonValue({ value, highlighted = false }: { value: HomeComparisonValue; highlighted?: boolean }) {
  if (value === '—') return <><span className="sr-only">Not included as a first-class feature</span><span aria-hidden="true">—</span></>;
  if (value === '✓') {
    if (!highlighted) return <><span className="sr-only">Available</span><span aria-hidden="true">✓</span></>;
    return <span className="interactive-compare-check"><span className="sr-only">Available</span><span aria-hidden="true">✓</span></span>;
  }
  return <span className={`interactive-compare-status${highlighted ? ' is-highlighted' : ''}`}>{value}</span>;
}

export function HomeProductComparison() {
  return (
    <section className="interactive-product-comparison" data-home-section="comparison" aria-labelledby="interactive-overleaf-title">
      <div className="interactive-page-container">
        <div className="interactive-section-heading interactive-centered-heading">
          <span className="interactive-eyebrow">Learnitive vs Overleaf</span>
          <h2 id="interactive-overleaf-title">Switching from Overleaf?</h2>
          <p>Both support serious LaTeX writing. Learnitive extends the workflow with Markdown, local-first projects, research tools, AI, learning features and advanced project tools around files you control.</p>
        </div>
        <div className="interactive-table-scroll interactive-product-comparison-table">
          <table className="interactive-compare-table">
            <thead><tr><th scope="col">Feature</th><th scope="col" className="interactive-compare-learnitive">Learnitive</th><th scope="col">Overleaf</th></tr></thead>
            <tbody>{PRODUCT_COMPARISON.map(([feature, learnitive, overleaf]) => <tr key={feature}><th scope="row">{feature}</th><td className="interactive-compare-learnitive"><ComparisonValue value={learnitive} highlighted /></td><td><ComparisonValue value={overleaf} /></td></tr>)}</tbody>
          </table>
        </div>
        <div className="interactive-product-comparison-mobile" aria-label="Learnitive and Overleaf feature comparison">
          {PRODUCT_COMPARISON.map(([feature, learnitive, overleaf]) => (
            <article key={feature}>
              <h3>{feature}</h3>
              <dl>
                <div className="interactive-compare-mobile-primary"><dt>Learnitive</dt><dd><ComparisonValue value={learnitive} highlighted /></dd></div>
                <div><dt>Overleaf</dt><dd><ComparisonValue value={overleaf} /></dd></div>
              </dl>
            </article>
          ))}
        </div>
        <div className="interactive-comparison-cta">
          <a className="interactive-button interactive-button-primary" href="/projects">Import your Overleaf project <ArrowRight className="size-4" aria-hidden="true" /></a>
          <p>Export your Overleaf project as a ZIP, then choose <strong>Import ZIP</strong> in Learnitive.</p>
          <div className="interactive-comparison-links">
            <a className="interactive-text-link" href="/compare/overleaf">Compare Learnitive and Overleaf <ArrowRight className="size-4" aria-hidden="true" /></a>
            <a className="interactive-text-link" href="/compare">View all comparisons <ArrowRight className="size-4" aria-hidden="true" /></a>
          </div>
        </div>
      </div>
    </section>
  );
}

const FEATURE_GROUPS: readonly { title: string; copy: string; cards: readonly { title: string; copy: string; icon: LucideIcon; highlights: readonly string[] }[] }[] = [
  {
    title: 'Writing',
    copy: 'Create portable documents in Markdown with a visual editing workflow when you want it.',
    cards: [
      { title: 'Markdown Writer', copy: 'Write notes, articles, documentation and long-form projects in ordinary Markdown files.', icon: FileCode2, highlights: ['Portable Markdown', 'Headings and lists', 'Tables and links', 'Images', 'Document outline'] },
      { title: 'Visual Editing', copy: 'Use a document-focused WYSIWYG experience without giving up access to the underlying source.', icon: PanelsTopLeft, highlights: ['Visual mode', 'Source mode', 'Structured blocks', 'Keyboard workflow'] },
      { title: 'Document Projects', copy: 'Keep related files together as a project rather than reducing your work to a single cloud document.', icon: FolderOpen, highlights: ['Multi-file projects', 'Browser storage', 'Projects Folder', 'Portable source'] },
      { title: 'Templates', copy: 'Start from writing and academic structures instead of coding frameworks.', icon: LayoutTemplate, highlights: ['Documents', 'Articles', 'Books', 'Reports', 'Academic starters'] },
    ],
  },
  {
    title: 'LaTeX and Research',
    copy: 'Treat academic and technical writing as a first-class workflow.',
    cards: [
      { title: 'LaTeX Source + Visual', copy: 'Move between manuscript-focused editing and direct LaTeX source around the same project.', icon: FileCode2, highlights: ['Visual mode', 'Source mode', 'Math', 'Tables and lists'] },
      { title: 'PDF Publishing', copy: 'Compile and inspect publication-ready output without leaving the project.', icon: FileCheck2, highlights: ['PDF preview', 'Compiler logs', 'SyncTeX', 'Multiple engines'] },
      { title: 'Citations & Bibliography', copy: 'Keep BibTeX/Biber files and citations close to the manuscript.', icon: Quote, highlights: ['BibTeX', 'Biber', 'Citations', 'Reference files'] },
      { title: 'Paper Memory', copy: 'Keep source-grounded research context available while drafting and revising.', icon: BookOpen, highlights: ['Research context', 'Source memory', 'Reference workflow', 'Project continuity'] },
    ],
  },
  {
    title: 'AI Assistance',
    copy: 'Use AI as an explicit writing and research tool, with provider choice under your control.',
    cards: [
      { title: 'AI Writer', copy: 'Draft, rewrite, explain, summarise and restructure text with project context.', icon: Brain, highlights: ['Drafting', 'Rewrite', 'Summaries', 'Project context'] },
      { title: 'Local AI', copy: 'Use supported local models when you want a local model path.', icon: ShieldCheck, highlights: ['Local models', 'Explicit choice', 'No silent cloud fallback'] },
      { title: 'BYOK', copy: 'Connect supported cloud AI providers with your own key on Pro when a cloud model is useful.', icon: Brain, highlights: ['Provider choice', 'Your API key', 'Explicit cloud use'] },
    ],
  },
  {
    title: 'Ownership and Collaboration',
    copy: 'Keep your files portable and choose when online services add value.',
    cards: [
      { title: 'Local First', copy: 'Use browser projects and supported Projects Folder synchronization without making permanent cloud storage the only source of truth.', icon: FolderOpen, highlights: ['Browser projects', 'Projects Folder', 'Portable files', 'Local ownership'] },
      { title: 'Collaboration', copy: 'Share authenticated project access when you want to work together around a document.', icon: Users, highlights: ['Authenticated access', 'Presence', 'Review', 'Project sharing'] },
      { title: 'Learning', copy: 'Extend the same project model into guided learning, with Tutor and Whiteboard planned as separate Learnitive applications.', icon: BookOpen, highlights: ['Learn courses', 'Future Tutor', 'Future Whiteboard', 'Project-based learning'] },
    ],
  },
] as const;

export function FeaturesPageContent() {
  return <>
    <header className="interactive-page-container interactive-feature-page-hero">
      <span className="interactive-eyebrow">Features</span>
      <h1>Features</h1>
      <p>Markdown and visual writing, LaTeX and PDF publishing, citations, research tools, local-first projects, AI assistance and learning in one workspace.</p>
      <div className="interactive-hero-actions"><a className="interactive-button interactive-button-primary interactive-button-lg" href="/projects">Open Workspace <ArrowRight className="size-4" aria-hidden="true" /></a><a className="interactive-button interactive-button-secondary interactive-button-lg" href="/templates">Browse Templates</a></div>
    </header>
    {FEATURE_GROUPS.map((group) => <section className="interactive-page-container interactive-features-card-section interactive-feature-group" aria-labelledby={`interactive-feature-${group.title.replace(/\W+/gu, '-').toLowerCase()}`} key={group.title}>
      <div className="interactive-section-heading interactive-centered-heading interactive-features-grid-heading">
        <h2 id={`interactive-feature-${group.title.replace(/\W+/gu, '-').toLowerCase()}`}>{group.title}</h2>
        <p>{group.copy}</p>
      </div>
      <div className="interactive-features-card-grid">
        {group.cards.map((feature) => {
          const Icon = feature.icon;
          const softwareHref = feature.title === 'Software Catalog' ? '/software-list' : undefined;
          return <article className="interactive-feature-card-v2" key={feature.title}>
            <span className="interactive-feature-card-icon" aria-hidden="true"><Icon className="size-6" /></span>
            <h3>{feature.title}</h3>
            <p>{feature.copy}</p>
            <ul>{feature.highlights.map((highlight) => <li key={highlight}><CircleCheckBig className="size-4" aria-hidden="true" /><span>{highlight}</span></li>)}</ul>
            {softwareHref ? <a className="interactive-text-link" href={softwareHref}>View Software <ArrowRight className="size-4" aria-hidden="true" /></a> : null}
          </article>;
        })}
      </div>
    </section>)}
    <PublicFinalCta heading="Start Writing" copy="Open a Markdown or LaTeX project and keep your source portable from the first draft." secondaryLabel="Browse Templates" secondaryHref="/templates" />
  </>;
}

export type CompareCompetitorSlug = string;
export type CompareGuideSlug = string;

type CompareCell = string;
type CompareStrength = { title: string; copy: string; icon: LucideIcon };
type CompareCompetitor = {
  slug: CompareCompetitorSlug;
  name: string;
  category: string;
  eyebrow: string;
  summary: string;
  website: string;
  pricingUrl: string;
  pricing: string;
  lastVerified: string;
  seoTitle: string;
  seoDescription: string;
  strengths: readonly CompareStrength[];
  rows: readonly (readonly [string, CompareCell, CompareCell])[];
  differences: readonly string[];
  fit: readonly string[];
  migration: readonly string[];
  migrationCopy?: string;
  fitHeading?: string;
  differencesHeading?: string;
  ctaCopy?: string;
  faq: readonly (readonly [string, string])[];
  rowSourceIds: Readonly<Record<string, readonly string[]>>;
  sources: readonly { id: string; label: string; url: string }[];
};

type CompareGuide = {
  slug: CompareGuideSlug;
  title: string;
  eyebrow: string;
  summary: string;
  seoTitle: string;
  seoDescription: string;
  competitorSlugs: readonly string[];
  methodology: string;
  verdicts: readonly (readonly [string, string, string])[];
  faq: readonly (readonly [string, string])[];
};

const COMPARE_ICON_MAP: Readonly<Record<string, LucideIcon>> = Object.freeze({
  book: BookOpen,
  brain: Brain,
  code: FileCode2,
  folder: FolderOpen,
  panels: PanelsTopLeft,
  shield: ShieldCheck,
  terminal: SquareTerminal,
  users: Users,
  zap: Zap,
});

function compareIcon(name: string): LucideIcon {
  return COMPARE_ICON_MAP[name] ?? FileCheck2;
}

function compareRowSourceIds(
  input: Readonly<Record<string, readonly string[] | undefined>>,
): Readonly<Record<string, readonly string[]>> {
  const normalized: Record<string, readonly string[]> = {};
  for (const [feature, sourceIds] of Object.entries(input)) {
    if (!sourceIds) continue;
    normalized[feature] = sourceIds.map((sourceId) => String(sourceId));
  }
  return normalized;
}

export const COMPARE_COMPETITORS: readonly CompareCompetitor[] = compareContent.competitors.map((item) => ({
  ...item,
  strengths: item.strengths.map((strength) => ({ ...strength, icon: compareIcon(strength.icon) })),
  rows: item.rows.map((row) => [String(row[0] ?? ''), String(row[1] ?? ''), String(row[2] ?? '')] as const),
  faq: item.faq.map((entry) => [String(entry[0] ?? ''), String(entry[1] ?? '')] as const),
  rowSourceIds: compareRowSourceIds(item.rowSourceIds),
}));

export const COMPARE_GUIDES: readonly CompareGuide[] = compareContent.guides.map((guide) => ({
  ...guide,
  competitorSlugs: guide.competitorSlugs.map((slug) => String(slug)),
  verdicts: guide.verdicts.map((entry) => [String(entry[0] ?? ''), String(entry[1] ?? ''), String(entry[2] ?? '')] as const),
  faq: guide.faq.map((entry) => [String(entry[0] ?? ''), String(entry[1] ?? '')] as const),
}));

const LATEX_COMPARE_COMPETITORS = COMPARE_COMPETITORS.filter((item) => item.category === 'latex');

const COMPARE_HUB_STRENGTHS = [
  { title: 'Markdown + LaTeX', copy: 'Move between general writing and academic LaTeX projects without changing products.', icon: BookOpen },
  { title: 'Local-first projects', copy: 'Keep portable project files in browser storage or linked local folders instead of making hosted storage the only source of truth.', icon: FolderOpen },
  { title: 'Research + citations', copy: 'Keep papers, evidence, bibliography and document context close to the writing workflow.', icon: Quote },
  { title: 'AI your way', copy: 'Use Local AI and Ollama, or unlock BYOK providers with Pro when a cloud model is useful.', icon: Brain },
] as const;

function comparisonStatusTone(value: string): 'positive' | 'neutral' | 'negative' {
  if (value === 'Yes' || value.startsWith('Configurable') || value.startsWith('Browser-local')) return 'positive';
  if (value === 'No') return 'negative';
  return 'neutral';
}

function DetailedComparisonValue({ value, highlighted = false }: { value: CompareCell; highlighted?: boolean }) {
  const tone = comparisonStatusTone(value);
  return <span className={`interactive-compare-status is-${tone}${highlighted ? ' is-highlighted' : ''}`}>
    {tone === 'positive' ? (highlighted ? <span className="interactive-compare-tick" aria-hidden="true"><Check className="size-3.5" /></span> : <CircleCheckBig className="size-4" aria-hidden="true" />) : null}
    <span>{value}</span>
  </span>;
}

function compareVerifiedLabel(value: string): string {
  const date = new Date(`${value}T00:00:00Z`);
  if (Number.isNaN(date.getTime())) return value;
  return new Intl.DateTimeFormat('en-AU', { day: 'numeric', month: 'long', year: 'numeric', timeZone: 'UTC' }).format(date);
}

function CompareDirectoryCards({ competitors = COMPARE_COMPETITORS }: { competitors?: readonly CompareCompetitor[] }) {
  return <div className="interactive-compare-directory-grid">{competitors.map((item) => <a className="interactive-compare-directory-card" key={item.slug} href={`/compare/${item.slug}`}>
    <span className="interactive-eyebrow">{item.eyebrow}</span>
    <h3>Learnitive vs {item.name}</h3>
    <p>{item.summary}</p>
    <span className="interactive-text-link">Read comparison <ArrowRight className="size-4" aria-hidden="true" /></span>
  </a>)}</div>;
}

export function CompareIndexPageContent() {
  return <>
    <header className="interactive-page-container interactive-compare-hero">
      <span className="interactive-eyebrow">Compare</span>
      <h1>Compare Learnitive</h1>
      <p>Compare Learnitive with established LaTeX and research-writing tools, with sourced claims and review dates for competitor facts.</p>
      <div className="interactive-hero-actions"><a className="interactive-button interactive-button-primary interactive-button-lg" href="/projects">Open Workspace <ArrowRight className="size-4" aria-hidden="true" /></a><a className="interactive-button interactive-button-secondary interactive-button-lg" href="/templates">Browse Templates</a></div>
    </header>
    <section className="interactive-page-container interactive-compare-strengths" aria-labelledby="compare-strengths-title">
      <div className="interactive-section-heading interactive-centered-heading"><span className="interactive-eyebrow">Learn · Research · Write</span><h2 id="compare-strengths-title">A broader writing workspace</h2><p>Learnitive combines Markdown, LaTeX, local-first project ownership, research context and optional AI in one workspace.</p></div>
      <div className="interactive-compare-strength-grid">{COMPARE_HUB_STRENGTHS.map((item) => { const Icon = item.icon; return <article key={item.title}><span aria-hidden="true"><Icon className="size-5" /></span><h3>{item.title}</h3><p>{item.copy}</p></article>; })}</div>
    </section>
    <section className="interactive-page-container interactive-compare-directory" aria-labelledby="compare-directory-title">
      <div className="interactive-section-heading interactive-centered-heading"><span className="interactive-eyebrow">LaTeX and research</span><h2 id="compare-directory-title">Writing-tool comparisons</h2><p>Explore sourced comparisons with Overleaf and other specialist LaTeX/research editors.</p></div>
      <CompareDirectoryCards competitors={LATEX_COMPARE_COMPETITORS} />
    </section>
    <section className="interactive-page-container interactive-compare-directory" aria-labelledby="compare-guides-title">
      <div className="interactive-section-heading interactive-centered-heading"><span className="interactive-eyebrow">Decision guides</span><h2 id="compare-guides-title">LaTeX and research guides</h2></div>
      <div className="interactive-compare-directory-grid">{COMPARE_GUIDES.map((guide) => <a className="interactive-compare-directory-card" key={guide.slug} href={`/compare/${guide.slug}`}><span className="interactive-eyebrow">{guide.eyebrow}</span><h3>{guide.title}</h3><p>{guide.summary}</p><span className="interactive-text-link">Open guide <ArrowRight className="size-4" aria-hidden="true" /></span></a>)}</div>
    </section>
    <PublicFinalCta heading="Choose the workflow that fits" copy="Import an existing LaTeX ZIP or start a new Markdown or LaTeX project." primaryLabel="Open Workspace" primaryHref="/projects" secondaryLabel="Browse Templates" secondaryHref="/templates" />
  </>;
}

export function CompareGuidePageContent({ slug }: { slug: CompareGuideSlug }) {
  const guide = COMPARE_GUIDES.find((entry) => entry.slug === slug);
  if (!guide) return null;
  const included = new Set(guide.competitorSlugs);
  const filtered = COMPARE_COMPETITORS.filter((item) => included.has(item.slug));
  return <>
    <header className="interactive-page-container interactive-compare-detail-hero">
      <a className="interactive-text-link interactive-compare-back" href="/compare">← Compare editors</a>
      <span className="interactive-eyebrow">{guide.eyebrow}</span>
      <h1>{guide.title}</h1>
      <p>{guide.summary}</p>
    </header>
    <section className="interactive-page-container interactive-compare-detail-section" aria-labelledby={`guide-${guide.slug}-verdicts`}>
      <div className="interactive-section-heading interactive-centered-heading"><span className="interactive-eyebrow">Quick verdicts</span><h2 id={`guide-${guide.slug}-verdicts`}>Best fit by workflow</h2><p>{guide.methodology}</p></div>
      <div className="interactive-compare-strength-grid">{guide.verdicts.map(([priority, product, reason]) => <article key={`${priority}-${product}`}><p className="interactive-compare-fit-label">{priority}</p><h3>{product}</h3><p>{reason}</p></article>)}</div>
    </section>
    <section className="interactive-page-container interactive-compare-directory" aria-labelledby={`guide-${guide.slug}-title`}>
      <div className="interactive-section-heading interactive-centered-heading"><span className="interactive-eyebrow">Detailed comparisons</span><h2 id={`guide-${guide.slug}-title`}>Editors in this guide</h2><p>Open a direct comparison for dated competitor facts, pricing and migration notes.</p></div>
      <CompareDirectoryCards competitors={filtered} />
    </section>
    <PublicFaq title="Comparison FAQs" items={guide.faq} />
    <PublicFinalCta heading="Try Learnitive with your project" copy="Import an existing LaTeX ZIP or start from a template." />
  </>;
}

export function CompareDetailPageContent({ slug, freeProjectLimit }: { slug: CompareCompetitorSlug; freeProjectLimit?: number }) {
  const item = COMPARE_COMPETITORS.find((entry) => entry.slug === slug);
  if (!item) return null;
  const effectiveFreeProjectLimit = normalizedPublicFreeProjectLimit(freeProjectLimit);
  const lifetime = LEARNITIVE_PRICING_PLANS.find((plan) => plan.id === 'lifetime');
  const monthly = LEARNITIVE_PRICING_PLANS.find((plan) => plan.id === 'monthly');
  const migrationHref = undefined;
  return <>
    <header className="interactive-page-container interactive-compare-detail-hero">
      <a className="interactive-text-link interactive-compare-back" href="/compare">← Compare</a>
      <span className="interactive-eyebrow">{item.eyebrow}</span>
      <h1>Learnitive vs {item.name}</h1>
      <p>{item.summary}</p>
      <div className="interactive-hero-actions"><a className="interactive-button interactive-button-primary interactive-button-lg" href="/projects">Open Learnitive <ArrowRight className="size-4" aria-hidden="true" /></a>{migrationHref ? <a className="interactive-button interactive-button-secondary interactive-button-lg" href={migrationHref}>Move from {item.name}</a> : <a className="interactive-button interactive-button-secondary interactive-button-lg" href={item.website} target="_blank" rel="noopener noreferrer">Visit {item.name}</a>}</div>
    </header>
    <section className="interactive-page-container interactive-compare-detail-section" aria-labelledby={`why-interactive-${item.slug}`}>
      <div className="interactive-section-heading interactive-centered-heading"><span className="interactive-eyebrow">Learnitive</span><h2 id={`why-interactive-${item.slug}`}>Key Strengths</h2></div>
      <div className="interactive-compare-strength-grid">{item.strengths.map((entry) => { const Icon = entry.icon; return <article key={entry.title}><span aria-hidden="true"><Icon className="size-5" /></span><h3>{entry.title}</h3><p>{entry.copy}</p></article>; })}</div>
    </section>
    <section className="interactive-page-container interactive-compare-detail-section" aria-labelledby={`feature-compare-${item.slug}`}>
      <div className="interactive-section-heading interactive-centered-heading"><span className="interactive-eyebrow">Features</span><h2 id={`feature-compare-${item.slug}`}>At a Glance</h2><p>Plan-dependent and unverified capabilities are labelled explicitly.</p></div>
      <div className="interactive-table-scroll interactive-compare-detail-table"><table className="interactive-compare-table"><thead><tr><th scope="col">Capability</th><th scope="col" className="interactive-compare-learnitive">Learnitive</th><th scope="col">{item.name}</th></tr></thead><tbody>{item.rows.map(([feature, learnitive, competitor]) => <tr key={feature}><th scope="row">{feature}</th><td className="interactive-compare-learnitive"><DetailedComparisonValue value={learnitive} highlighted /></td><td><DetailedComparisonValue value={competitor} /></td></tr>)}</tbody></table></div>
    </section>
    <section className="interactive-page-container interactive-compare-two-column">
      <article><span className="interactive-eyebrow">Differences</span><h2>{item.differencesHeading || 'Key Differences'}</h2><ul>{item.differences.map((point) => <li key={point}><CircleCheckBig className="size-4" aria-hidden="true" /><span>{point}</span></li>)}</ul></article>
      <article><span className="interactive-eyebrow">Good Fit</span><h2>{item.fitHeading || 'Best Fit'}</h2><ul>{item.fit.map((point) => <li key={point}><CircleCheckBig className="size-4" aria-hidden="true" /><span>{point}</span></li>)}</ul></article>
    </section>
    <section className="interactive-page-container interactive-compare-detail-section" aria-labelledby={`migration-${item.slug}`}>
      <div className="interactive-section-heading interactive-centered-heading"><span className="interactive-eyebrow">Migration</span><h2 id={`migration-${item.slug}`}>Move from {item.name}</h2><p>{item.migrationCopy || 'Move the project files, then verify the project in Learnitive.'}</p></div>
      <ol className="interactive-compare-migration">{item.migration.map((step, index) => <li key={step}><span aria-hidden="true">{index + 1}</span><p>{step}</p></li>)}</ol>
      {migrationHref ? <div className="interactive-section-action"><a className="interactive-button interactive-button-secondary" href={migrationHref}>Full Migration Guide <ArrowRight className="size-4" aria-hidden="true" /></a></div> : null}
    </section>
    <section className="interactive-page-container interactive-compare-pricing" aria-labelledby={`pricing-compare-${item.slug}`}>
      <div className="interactive-section-heading interactive-centered-heading"><h2 id={`pricing-compare-${item.slug}`}>Pricing</h2></div>
      <div className="interactive-compare-pricing-grid"><article className="is-learnitive"><h3>Learnitive</h3><p><strong>Free:</strong> $0 forever · up to {effectiveFreeProjectLimit} projects</p><p><strong>Pro Lifetime:</strong> {lifetime?.price ?? '$29 one-time'}</p><p><strong>Pro Monthly:</strong> {monthly?.price ?? '$5 / month'}</p><a className="interactive-text-link" href="/pricing">View Pricing <ArrowRight className="size-4" aria-hidden="true" /></a></article><article><h3>{item.name}</h3><p>{item.pricing}</p><a className="interactive-text-link" href={item.pricingUrl} target="_blank" rel="noopener noreferrer">Check Current {item.name} Pricing <ArrowRight className="size-4" aria-hidden="true" /></a></article></div>
      <p className="interactive-compare-reviewed">Competitor information last reviewed {compareVerifiedLabel(item.lastVerified)}. Features and prices change; check the official sources below.</p>
    </section>
    <PublicFaq title={`${item.name} FAQs`} items={item.faq} freeProjectLimit={effectiveFreeProjectLimit} />
    <section className="interactive-page-container interactive-compare-detail-section" aria-labelledby={`sources-${item.slug}`}>
      <div className="interactive-section-heading interactive-centered-heading"><span className="interactive-eyebrow">Sources</span><h2 id={`sources-${item.slug}`}>Official Sources</h2><p>Reviewed against provider-controlled sources on {compareVerifiedLabel(item.lastVerified)}.</p></div>
      <ul className="interactive-compare-sources">{item.sources.map((source) => <li key={source.url}><a className="interactive-text-link" href={source.url} target="_blank" rel="noopener noreferrer">{source.label} <ArrowRight className="size-4" aria-hidden="true" /></a></li>)}</ul>
    </section>
    <PublicFinalCta heading="Try Learnitive" copy={item.ctaCopy || 'Bring your project through ZIP, Git or a local folder.'} primaryLabel="Open Projects" primaryHref="/projects" secondaryLabel="All Comparisons" secondaryHref="/compare" />
  </>;
}

export type MigrationPlatformSlug = string;
type MigrationPlatform = {
  slug: MigrationPlatformSlug;
  name: string;
  category: string;
  seoTitle: string;
  seoDescription: string;
  difficulty: string;
  recommendedMethods: readonly string[];
  summary: string;
  before: readonly string[];
  steps: readonly { title: string; copy: string }[];
  mapping: readonly (readonly [string, string])[];
  verification: readonly string[];
  issues: readonly { title: string; copy: string }[];
  notes: readonly string[];
  compareSlug: string;
  relatedDocs: readonly string[];
  lastReviewed: string;
};

export const MIGRATION_PLATFORMS: readonly MigrationPlatform[] = migrationContent.platforms.map((item) => ({
  ...item,
  recommendedMethods: item.recommendedMethods.map(String),
  before: item.before.map(String),
  steps: item.steps.map((step) => ({ title: String(step.title), copy: String(step.copy) })),
  mapping: item.mapping.map((row) => [String(row[0] ?? ''), String(row[1] ?? '')] as const),
  verification: item.verification.map(String),
  issues: item.issues.map((entry) => ({ title: String(entry.title), copy: String(entry.copy) })),
  notes: item.notes.map(String),
  relatedDocs: item.relatedDocs.map(String),
}));

export function MigrationIndexPageContent() {
  const groups = [
    ['Cloud and Browser IDEs', ['replit','codepen','codesandbox','stackblitz','github-codespaces','gitpod']],
    ['AI Editors', ['cursor','windsurf']],
    ['AI App Builders', ['bolt','lovable']],
    ['Developer Tools', ['vscode']],
    ['Research', ['overleaf','jupyter']],
  ] as const;
  return <>
    <header className="interactive-page-container interactive-compare-hero">
      <span className="interactive-eyebrow">Migrate</span>
      <h1>Move to Learnitive</h1>
      <p>Bring projects from popular IDEs, AI editors, app builders and research tools using Git, ZIP or local folders.</p>
      <div className="interactive-hero-actions"><a className="interactive-button interactive-button-primary interactive-button-lg" href="/projects">Open Workspace <ArrowRight className="size-4" aria-hidden="true" /></a><a className="interactive-button interactive-button-secondary interactive-button-lg" href="/compare">Compare Platforms</a></div>
    </header>
    {groups.map(([title, slugs]) => {
      const set = new Set<string>(slugs);
      const rows = MIGRATION_PLATFORMS.filter((item) => set.has(item.slug));
      return <section className="interactive-page-container interactive-migrate-group" key={title} aria-labelledby={`migrate-${title.replace(/\W+/gu,'-').toLowerCase()}`}>
        <div className="interactive-migrate-group-heading"><h3 id={`migrate-${title.replace(/\W+/gu,'-').toLowerCase()}`}>{title}</h3><small>{rows.length} {rows.length===1?'item':'items'}</small></div>
        <div className="interactive-migrate-grid">{rows.map((item) => <a className="interactive-migrate-card" href={`/migrate/${item.slug}`} key={item.slug}><span className="interactive-eyebrow">{item.category}</span><h3>{item.name}</h3><p>{item.summary}</p><div><span>{item.difficulty}</span><span>{item.recommendedMethods.join(' · ')}</span></div><span className="interactive-text-link">Migration Guide <ArrowRight className="size-4" aria-hidden="true" /></span></a>)}</div>
      </section>;
    })}
    <PublicFinalCta heading="Bring Your Project" copy="Open a project now, or compare platforms before you move." primaryLabel="Open Projects" primaryHref="/projects" secondaryLabel="Compare" secondaryHref="/compare" />
  </>;
}

export function MigrationDetailPageContent({ slug }: { slug: MigrationPlatformSlug }) {
  const item = MIGRATION_PLATFORMS.find((entry) => entry.slug === slug);
  if (!item) return null;
  return <article className="interactive-migrate-detail">
    <header className="interactive-page-container interactive-compare-detail-hero">
      <a className="interactive-text-link interactive-compare-back" href="/migrate">← Migration Guides</a>
      <span className="interactive-eyebrow">{item.category}</span>
      <h1>Move from {item.name}</h1>
      <p>{item.summary}</p>
      <div className="interactive-migrate-meta"><span><strong>Typical migration:</strong> {item.difficulty}</span><span><strong>Best method:</strong> {item.recommendedMethods.join(' · ')}</span></div>
    </header>
    <section className="interactive-page-container interactive-migrate-section"><div className="interactive-section-heading"><h2>Before You Move</h2></div><ul className="interactive-migrate-checklist">{item.before.map((entry) => <li key={entry}><CircleCheckBig className="size-4" aria-hidden="true" /><span>{entry}</span></li>)}</ul></section>
    <section className="interactive-page-container interactive-migrate-section"><div className="interactive-section-heading"><h2>Migration Steps</h2></div><ol className="interactive-migrate-steps">{item.steps.map((step,index)=><li key={step.title}><span>{String(index+1).padStart(2,'0')}</span><div><h3>{step.title}</h3><p>{step.copy}</p></div></li>)}</ol></section>
    <section className="interactive-page-container interactive-migrate-section"><div className="interactive-section-heading"><h2>Where Things Go</h2></div><div className="interactive-table-scroll interactive-migrate-mapping"><table className="interactive-compare-table"><thead><tr><th scope="col">{item.name}</th><th scope="col">Learnitive</th></tr></thead><tbody>{item.mapping.map(([source,target])=><tr key={source}><th scope="row">{source}</th><td>{target}</td></tr>)}</tbody></table></div></section>
    <section className="interactive-page-container interactive-compare-two-column"><article><span className="interactive-eyebrow">Verify</span><h2>Check the Project</h2><ul>{item.verification.map((entry)=><li key={entry}><CircleCheckBig className="size-4" aria-hidden="true" /><span>{entry}</span></li>)}</ul></article><article><span className="interactive-eyebrow">Common Issues</span><h2>Watch For</h2><ul>{item.issues.map((entry)=><li key={entry.title}><div><strong>{entry.title}</strong><span>{entry.copy}</span></div></li>)}</ul></article></section>
    <section className="interactive-page-container interactive-migrate-section"><div className="interactive-section-heading"><h2>Related Guides</h2></div><div className="interactive-about-links"><a className="interactive-text-link" href={`/compare/${item.compareSlug}`}>Learnitive vs {item.name} <ArrowRight className="size-4" aria-hidden="true" /></a>{item.relatedDocs.map((href)=><a className="interactive-text-link" href={href} key={href}>Open Docs <ArrowRight className="size-4" aria-hidden="true" /></a>)}</div><p className="interactive-compare-reviewed">Migration guide last reviewed {compareVerifiedLabel(item.lastReviewed)}.</p></section>
    <PublicFinalCta heading="Continue in Learnitive" copy="Open the migrated project and verify it in the IDE, terminal and preview." primaryLabel="Open Projects" primaryHref="/projects" secondaryLabel="Compare Platforms" secondaryHref="/compare" />
  </article>;
}

export function HomeDifferentiators() {
  const items = [
    { title: 'Files you control', copy: 'Use Browser storage, optional Projects Folder synchronization, ZIP and Git workflows around ordinary LaTeX project files.', icon: FolderOpen },
    { title: 'Compile where you write', copy: 'Run local LaTeX compilation in the browser and inspect PDF, logs and SyncTeX in the same workspace.', icon: Zap },
    { title: 'Research tools nearby', copy: 'Keep citations, papers, code and review workflows close to the manuscript instead of in separate silos.', icon: History },
  ] as const;
  return <section className="interactive-page-container interactive-home-differentiators" aria-label="Why Learnitive">{items.map((item) => { const Icon = item.icon; return <article key={item.title}><Icon className="size-5" aria-hidden="true" /><div><h2>{item.title}</h2><p>{item.copy}</p></div></article>; })}</section>;
}
