import React, { useDeferredValue, useEffect, useState } from 'react'
import { usePage } from '@inertiajs/react'
import DocsCallout from '../../components/docs/DocsCallout'
import DocsSection from '../../components/docs/DocsSection'
import DocsSidebarNav from '../../components/docs/DocsSidebarNav'
import DocsStepList from '../../components/docs/DocsStepList'
import HelpGuideCard from '../../components/help/HelpGuideCard'
import HelpSearchBar from '../../components/help/HelpSearchBar'
import HelpSupportCta from '../../components/help/HelpSupportCta'
import HelpTopicCard from '../../components/help/HelpTopicCard'
import SeoHead from '../../components/seo/SeoHead'
import {
  FEATURED_GUIDES,
  GETTING_STARTED_LINKS,
  GETTING_STARTED_STEPS,
  HELP_CATEGORIES,
  HIGHLIGHTED_GUIDES,
  POPULAR_HELP_TOPICS,
  SEARCH_SUGGESTIONS,
  SUPPORT_ITEMS,
  TROUBLESHOOTING_ITEMS,
} from './helpCenterContent'

function matchesQuery(item, query) {
  if (!query) return true

  const haystack = [
    item.title,
    item.description,
    item.status,
    item.eyebrow,
    item.plannedPath,
    ...(item.tags || []),
    ...(item.highlights || []),
    ...(item.linkItems || []).map((linkItem) => linkItem.label),
  ].filter(Boolean).join(' ').toLowerCase()

  return haystack.includes(query)
}

function MiniLink({ item, href }) {
  return (
    <a href={href} className="rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]">
      {item.label}
    </a>
  )
}

function PopularTopicCard({ item, href }) {
  return (
    <a href={href} className="rounded-[24px] border border-white/10 bg-black/20 p-4 transition hover:border-white/20 hover:bg-white/[0.05]">
      <h3 className="text-base font-semibold text-white">{item.title}</h3>
      <p className="mt-2 text-sm leading-6 text-slate-300">{item.description}</p>
    </a>
  )
}

export default function HelpCenterPage() {
  const page = usePage()
  const { props, url } = page
  const links = props.links || {}
  const signedIn = Boolean(props.auth?.signed_in)
  const urlQuery = new URLSearchParams((url.split('?')[1] || '')).get('q') || ''
  const [query, setQuery] = useState(urlQuery)
  const normalizedQuery = useDeferredValue(query.trim().toLowerCase())

  useEffect(() => {
    setQuery(urlQuery)
  }, [urlQuery])

  const highlightedGuides = HIGHLIGHTED_GUIDES.filter((item) => matchesQuery(item, normalizedQuery))
  const featuredGuides = FEATURED_GUIDES.filter((item) => matchesQuery(item, normalizedQuery))
  const categories = HELP_CATEGORIES.map((category) => ({
    ...category,
    topics: category.topics.filter((topic) => matchesQuery(topic, normalizedQuery)),
  })).filter((category) => category.topics.length > 0)
  const troubleshootingItems = TROUBLESHOOTING_ITEMS.filter((item) => matchesQuery(item, normalizedQuery))
  const popularTopics = POPULAR_HELP_TOPICS.filter((item) => matchesQuery(item, normalizedQuery))

  const totalMatches = highlightedGuides.length
    + featuredGuides.length
    + troubleshootingItems.length
    + popularTopics.length
    + categories.reduce((sum, category) => sum + category.topics.length, 0)

  const resultSummary = normalizedQuery
    ? `Showing ${totalMatches} matching help items for “${query.trim()}”.`
    : 'Search across live guides, planned help topics, popular questions, and troubleshooting shortcuts.'

  const supportItems = SUPPORT_ITEMS.map((item) => ({
    ...item,
    href: links[item.linkKey],
  }))

  const jsonLd = [
    {
      '@context': 'https://schema.org',
      '@type': 'WebPage',
      name: 'Help Center',
      description: props.description,
      url: props.seo?.canonical,
    },
    {
      '@context': 'https://schema.org',
      '@type': 'ItemList',
      itemListElement: FEATURED_GUIDES.map((item, index) => ({
        '@type': 'ListItem',
        position: index + 1,
        name: item.title,
      })),
    },
  ]

  return (
    <main className="min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.18),_transparent_22%),radial-gradient(circle_at_bottom_right,_rgba(250,204,21,0.16),_transparent_22%),linear-gradient(180deg,_#020617_0%,_#030712_100%)] px-4 py-8 sm:px-6 lg:px-8">
      <SeoHead seo={props.seo || {}} title={props.title} description={props.description} jsonLd={jsonLd} />

      <div className="mx-auto max-w-[1480px]">
        <section id="introduction" className="rounded-[38px] border border-white/10 bg-[linear-gradient(140deg,rgba(15,23,42,0.94),rgba(15,23,42,0.72)),radial-gradient(circle_at_top_right,rgba(125,211,252,0.18),transparent_26%)] p-6 shadow-[0_32px_100px_rgba(2,6,23,0.34)] md:p-8 lg:p-10">
          <div className="grid gap-8 xl:grid-cols-[minmax(0,1fr)_360px]">
            <div>
              <p className="text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-200/80">Skinbase Help Center</p>
              <h1 className="mt-3 max-w-4xl text-4xl font-semibold tracking-[-0.04em] text-white md:text-5xl xl:text-6xl">Find the right guide, quickstart, FAQ, or fix without digging through scattered help.</h1>
              <p className="mt-5 max-w-3xl text-base leading-8 text-slate-300 md:text-lg">This is the central help hub for Skinbase. Use it to get started, find module-specific guidance, open the live Groups documentation set, and move quickly toward the next useful answer.</p>

              <div className="mt-6 flex flex-wrap gap-3">
                <a href="#featured-guides" className="rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100 transition hover:border-sky-300/40 hover:bg-sky-300/18">Browse help topics</a>
                <a href={links.groups_documentation} className="rounded-full border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.07]">Open Groups help</a>
                <a href={links.studio_help} className="rounded-full border border-white/10 bg-black/20 px-5 py-3 text-sm font-semibold text-slate-200 transition hover:border-white/20 hover:bg-white/[0.05]">Read Studio help</a>
              </div>

              <div className="mt-6 max-w-3xl">
                <HelpSearchBar
                  value={query}
                  onChange={setQuery}
                  onSelectSuggestion={setQuery}
                  onClear={() => setQuery('')}
                  suggestions={SEARCH_SUGGESTIONS}
                  resultSummary={resultSummary}
                />
              </div>
            </div>

            <div className="space-y-4">
              <div className="rounded-[30px] border border-white/10 bg-black/20 p-5">
                <p className="text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/80">Start here</p>
                <div className="mt-4 grid gap-3 sm:grid-cols-2 xl:grid-cols-1">
                  <a href={links.studio_help} className="rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-4 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.07]">Studio help</a>
                  <a href={links.upload_help} className="rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-4 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.07]">Upload help</a>
                  <a href={links.help_worlds} className="rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-4 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.07]">Worlds help</a>
                  <a href={links.help_cards} className="rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-4 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.07]">Cards help</a>
                  <a href={links.help_profile} className="rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-4 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.07]">Profile help</a>
                  <a href={links.help_auth} className="rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-4 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.07]">Signup / Login help</a>
                  <a href={links.help_troubleshooting} className="rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-4 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.07]">Troubleshooting help</a>
                  <a href={links.groups_quickstart} className="rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-4 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.07]">Groups Quickstart</a>
                  <a href={signedIn ? links.open_studio : links.login} className="rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-4 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.07]">{signedIn ? 'Open Studio workspace' : 'Sign in to start'}</a>
                </div>
              </div>
            </div>
          </div>
        </section>

        <div className="mt-8 grid gap-6 lg:grid-cols-[240px_minmax(0,1fr)] xl:grid-cols-[240px_minmax(0,1fr)_280px]">
          <DocsSidebarNav
            sections={[
              { id: 'highlighted-guides', label: 'Highlighted guides' },
              { id: 'featured-guides', label: 'Featured guides' },
              { id: 'help-categories', label: 'Help categories' },
              { id: 'getting-started', label: 'Getting started' },
              { id: 'troubleshooting', label: 'Troubleshooting' },
              { id: 'popular-topics', label: 'Popular topics' },
              { id: 'support-direction', label: 'Support direction' },
            ]}
            ariaLabel="Help center sections"
            selectLabel="Jump to help center section"
          />

          <div className="space-y-6">
            {normalizedQuery ? (
              <DocsCallout tone="note" title="Filtered help view">
                Search is filtering the live guides, planned topics, popular questions, and troubleshooting shortcuts below. Clear the search anytime to return to the full Help Center view.
              </DocsCallout>
            ) : (
              <DocsCallout tone="note" title="How to use the Help Center">
                Start with the highlighted live guides if you need complete written help now. Use the category sections to see the long-term help architecture and the next high-priority modules that will expand after Groups.
              </DocsCallout>
            )}

            <DocsSection
              id="highlighted-guides"
              eyebrow="Live now"
              title="Highlighted guides"
              summary="These are the strongest live help surfaces in the current Help Center. They show the quality bar and structural pattern the wider system will follow."
            >
              <div className="grid gap-4 xl:grid-cols-3">
                {highlightedGuides.map((item) => (
                  <HelpGuideCard key={item.title} item={item} links={links} />
                ))}
              </div>
            </DocsSection>

            <DocsSection
              id="featured-guides"
              eyebrow="Featured"
              title="Start with the highest-priority help topics"
              summary="These are the first modules users most often need help with. Groups is already live, while the rest are surfaced here with real product entry points and clean future help paths."
            >
              <div className="grid gap-4 xl:grid-cols-2">
                {featuredGuides.map((item) => (
                  <HelpGuideCard key={item.title} item={item} links={links} />
                ))}
              </div>
            </DocsSection>

            <section id="help-categories" className="space-y-6 scroll-mt-24">
              {categories.map((category) => (
                <DocsSection
                  key={category.id}
                  id={category.id}
                  eyebrow="Help category"
                  title={category.title}
                  summary={category.summary}
                >
                  <div className="grid gap-4 xl:grid-cols-2">
                    {category.topics.map((topic) => (
                      <HelpTopicCard key={topic.title} item={topic} links={links} />
                    ))}
                  </div>
                </DocsSection>
              ))}
            </section>

            <DocsSection
              id="getting-started"
              eyebrow="Onboarding"
              title="Getting started with Skinbase"
              summary="This path is designed for first-time creators who want a practical order of operations instead of a giant wall of documentation."
            >
              <div className="grid gap-6 xl:grid-cols-[minmax(0,1fr)_320px]">
                <DocsStepList items={GETTING_STARTED_STEPS} />

                <div className="space-y-3 rounded-[28px] border border-white/10 bg-black/20 p-5">
                  <p className="text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/80">Quick links</p>
                  <div className="grid gap-3">
                    {GETTING_STARTED_LINKS.map((item) => (
                      <MiniLink key={item.label} item={item} href={links[item.linkKey]} />
                    ))}
                  </div>
                </div>
              </div>
            </DocsSection>

            <DocsSection
              id="troubleshooting"
              eyebrow="Fixes first"
              title="Troubleshooting shortcuts"
              summary="These are the fast paths for users who are blocked and need a direct fix, not a longer article."
            >
              <div className="grid gap-4 xl:grid-cols-2">
                {troubleshootingItems.map((item) => (
                  <a key={item.title} href={links[item.linkKey]} className="rounded-[28px] border border-white/10 bg-black/20 p-5 transition hover:border-white/20 hover:bg-white/[0.05]">
                    <h3 className="text-lg font-semibold text-white">{item.title}</h3>
                    <p className="mt-3 text-sm leading-6 text-slate-300">{item.description}</p>
                    <div className="mt-4 flex items-center justify-between gap-3">
                      <span className="text-sm font-semibold text-sky-200">{item.linkLabel}</span>
                      <span className="text-slate-500">&rarr;</span>
                    </div>
                  </a>
                ))}
              </div>
            </DocsSection>

            <DocsSection
              id="popular-topics"
              eyebrow="Popular"
              title="Popular help topics"
              summary="These common journeys make the Help Center feel immediately useful even before every module-specific help page is fully written."
            >
              <div className="grid gap-4 xl:grid-cols-2">
                {popularTopics.map((item) => (
                  <PopularTopicCard key={item.title} item={item} href={links[item.linkKey]} />
                ))}
              </div>
            </DocsSection>

            <DocsSection
              id="support-direction"
              eyebrow="Next steps"
              title="Need more help than the hub can give?"
              summary="Use these routes when you need a person, need to report a product issue, or want the most complete live documentation surface right now."
            >
              <HelpSupportCta items={supportItems} />
            </DocsSection>
          </div>

          <aside className="hidden xl:block xl:sticky xl:top-24 xl:self-start">
            <div className="space-y-4 rounded-[28px] border border-white/10 bg-white/[0.03] p-5 shadow-[0_18px_50px_rgba(2,6,23,0.22)]">
              <div>
                <p className="text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/80">Help architecture</p>
                <ul className="mt-4 space-y-3 text-sm leading-6 text-slate-300">
                  <li>Use <span className="font-semibold text-white">/help</span> as the main hub.</li>
                  <li>Use <span className="font-semibold text-white">/help/topic</span> for overview pages.</li>
                  <li>Use <span className="font-semibold text-white">/help/topic/subpage</span> for quickstarts, FAQs, and troubleshooting.</li>
                </ul>
              </div>

              <div className="rounded-[24px] border border-white/10 bg-black/20 p-4">
                <p className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">Current coverage</p>
                <p className="mt-2 text-sm leading-6 text-slate-300">Groups is the first complete multi-page topic family, and Studio, Upload, Cards, Profile, Signup / Login, Account Settings, and Troubleshooting are now live topic guides. The rest of the Help Center still follows the same predictable expansion path.</p>
              </div>
            </div>
          </aside>
        </div>
      </div>
    </main>
  )
}