import React, { useMemo, useState } from 'react'
import WorldAnalyticsMetricGrid from './WorldAnalyticsMetricGrid'
import WorldAnalyticsSourceBreakdown from './WorldAnalyticsSourceBreakdown'
import WorldAnalyticsSectionPerformance from './WorldAnalyticsSectionPerformance'
import WorldAnalyticsParticipationPanel from './WorldAnalyticsParticipationPanel'
import WorldAnalyticsChallengePanel from './WorldAnalyticsChallengePanel'
import WorldAnalyticsEditionComparisonCard from './WorldAnalyticsEditionComparisonCard'

export default function WorldAnalyticsPanel({ analytics = null, world = null }) {
  const [activeRange, setActiveRange] = useState(analytics?.default_range || '30d')
  const range = useMemo(() => analytics?.ranges?.[activeRange] || analytics?.ranges?.[analytics?.default_range || '30d'] || null, [activeRange, analytics])

  if (!world?.id || !analytics || !range) {
    return (
      <div className="rounded-[24px] border border-dashed border-white/10 bg-white/[0.02] p-5 text-sm leading-6 text-slate-400">
        Analytics will populate after the world starts receiving traffic, clicks, submissions, or rewards.
      </div>
    )
  }

  return (
    <div className="grid gap-4">
      <div className="rounded-[24px] border border-white/10 bg-black/20 p-5">
        <div className="flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
          <div>
            <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">World analytics</div>
            <h3 className="mt-2 text-2xl font-semibold text-white">Campaign performance and editorial signals</h3>
            <p className="mt-2 max-w-3xl text-sm leading-6 text-slate-400">Traffic, promotion surfaces, engagement, participation, challenge energy, and recurring-edition readiness for this world.</p>
          </div>
          <div className="flex flex-wrap gap-2">
            {(analytics.range_options || []).map((option) => (
              <button
                key={option.value}
                type="button"
                onClick={() => setActiveRange(option.value)}
                className={`rounded-full border px-4 py-2 text-xs font-semibold uppercase tracking-[0.16em] transition ${activeRange === option.value ? 'border-sky-300/25 bg-sky-400/12 text-sky-100' : 'border-white/10 bg-white/[0.04] text-slate-300 hover:bg-white/[0.08]'}`}
              >
                {option.label}
              </button>
            ))}
          </div>
        </div>
      </div>

      <WorldAnalyticsMetricGrid summary={range.summary} />
      <WorldAnalyticsSourceBreakdown sources={range.sources} />
      <WorldAnalyticsSectionPerformance sections={range.section_performance} entities={range.entity_performance} />
      <WorldAnalyticsParticipationPanel participation={range.participation} />
      <WorldAnalyticsChallengePanel challenge={range.challenge} />
      <WorldAnalyticsEditionComparisonCard comparison={analytics.edition_comparison} />
    </div>
  )
}