import { useEffect, useState, useRef } from 'react';

const DATA_SOURCES = [
  {
    id: 'price-paid',
    name: 'Price Paid Data',
    origin: 'HM Land Registry',
    use: 'Complete historical property sale prices for England and Wales. Used for the last known sale price of each property.',
    url: 'https://www.gov.uk/government/statistical-data-sets/price-paid-data-downloads',
    license: 'Open Government Licence v3.0',
  },
  {
    id: 'epc',
    name: 'Energy Performance Certificates (EPC)',
    origin: 'Ministry of Housing, Communities & Local Government',
    use: 'Domestic Energy Performance Certificates providing floor area, number of rooms, construction age, energy ratings, property type, and built form. Fuzzy-joined with Price Paid records by address within postcode buckets.',
    url: 'https://epc.opendatacommunities.org/downloads/domestic',
    license: 'Open Government Licence v3.0',
  },
  {
    id: 'nspl',
    name: 'National Statistics Postcode Lookup (NSPL)',
    origin: 'ONS / ArcGIS',
    use: 'Maps postcodes to latitude/longitude, LSOA, and Output Area codes for geolocation and joining area-level datasets.',
    url: 'https://www.arcgis.com/sharing/rest/content/items/077631e063eb4e1ab43575d01381ec33/data',
    license: 'Open Government Licence v3.0',
  },
  {
    id: 'iod',
    name: 'English Indices of Deprivation 2025',
    origin: 'Ministry of Housing, Communities & Local Government',
    use: 'Relative deprivation scores for 33,755 LSOAs across domains: Income, Employment, Education, Health, Crime, Living Environment, and sub-domains. Joined to properties via LSOA code.',
    url: 'https://www.gov.uk/government/statistics/english-indices-of-deprivation-2025',
    license: 'Open Government Licence v3.0',
  },
  {
    id: 'ethnicity',
    name: 'Population by Ethnicity (2021 Census)',
    origin: 'ONS',
    use: 'Population percentages by ethnic group (Asian, Black, Mixed, White, Other) per Local Authority. Joined via Local Authority District code.',
    url: 'https://www.ethnicity-facts-figures.service.gov.uk/uk-population-by-ethnicity/national-and-regional-populations/regional-ethnic-diversity/latest/#download-the-data',
    license: 'Open Government Licence v3.0',
  },
  {
    id: 'crime',
    name: 'Street-level Crime Data',
    origin: 'data.police.uk',
    use: 'Street-level crime data from 2023 to 2025, aggregated into yearly averages by LSOA and crime type (violence, burglary, anti-social behaviour, drugs, vehicle crime, etc.).',
    url: 'https://data.police.uk/data/',
    license: 'Open Government Licence v3.0',
  },
  {
    id: 'tfl-journey-times',
    name: 'TfL Journey Times',
    origin: 'Transport for London',
    use: "Journey time calculations from postcodes to central London destinations (Bank, Waterloo, King's Cross, etc.) via public transport and cycling.",
    url: 'https://api-portal.tfl.gov.uk/',
    license: 'Powered by TfL Open Data',
  },
  {
    id: 'osm-pois',
    name: 'OpenStreetMap POIs',
    origin: 'OpenStreetMap contributors / Geofabrik',
    use: 'Points of interest extracted from the Great Britain PBF extract. Covers amenities, shops, healthcare, leisure, tourism, and more. Filtered and remapped to friendly category names.',
    url: 'https://download.geofabrik.de/europe/great-britain-latest.osm.pbf',
    license: 'Open Data Commons Open Database License (ODbL)',
  },
  {
    id: 'naptan',
    name: 'NaPTAN (Public Transport Stops)',
    origin: 'Department for Transport',
    use: 'National Public Transport Access Nodes providing station and stop locations (rail, bus, metro/tram, ferry, airport), merged into the POI dataset.',
    url: 'https://naptan.dft.gov.uk/naptan/schema/2.4/doc/NaPTANSchemaGuide-2.4-v0.57.pdf',
    license: 'Open Government Licence v3.0',
  },
  {
    id: 'noise',
    name: 'Defra Noise Mapping',
    origin: 'Defra / Environment Agency',
    use: 'Strategic noise mapping Round 4 (2022) for road, rail, and airport sources. Lden (day-evening-night 24h weighted average) at 10m grid resolution, modelled at 4m above ground. Sampled at postcode centroids via WCS GeoTIFF tiles.',
    url: 'https://environment.data.gov.uk/spatialdata/road-noise-all-metrics-england-round-4/wcs',
    license: 'Open Government Licence v3.0',
  },
  {
    id: 'ofsted',
    name: 'Ofsted School Inspections',
    origin: 'Ofsted',
    use: 'Latest inspection outcomes for state-funded schools (as at April 2025). Averaged per postcode to give a local school quality score (1=Outstanding to 4=Inadequate).',
    url: 'https://www.gov.uk/government/statistical-data-sets/monthly-management-information-ofsteds-school-inspections-outcomes',
    license: 'Open Government Licence v3.0',
  },
  {
    id: 'broadband',
    name: 'Ofcom Broadband Performance',
    origin: 'Ofcom',
    use: 'Fixed broadband coverage and speeds by Output Area from Connected Nations 2025. Includes max download/upload speeds across different speed tiers.',
    url: 'https://www.ofcom.org.uk/phones-and-broadband/coverage-and-speeds/connected-nations-20252/data-downloads-2025',
    license: 'Open Government Licence v3.0',
  },
  {
    id: 'council-tax',
    name: 'Council Tax Levels 2025-26',
    origin: 'Ministry of Housing, Communities & Local Government',
    use: 'Annual council tax rates for Bands A-H for all 296 billing authorities in England, for a dwelling occupied by two adults. Joined to properties via local authority district code from the NSPL postcode lookup.',
    url: 'https://www.gov.uk/government/statistics/council-tax-levels-set-by-local-authorities-in-england-2025-to-2026',
    license: 'Open Government Licence v3.0',
  },
];

export default function DataSourcesPage() {
  const [highlightedId, setHighlightedId] = useState<string | null>(null);
  const cardRefs = useRef<Record<string, HTMLDivElement | null>>({});

  useEffect(() => {
    function handleHash() {
      const hash = window.location.hash.replace('#', '');
      if (hash && DATA_SOURCES.some((s) => s.id === hash)) {
        setHighlightedId(hash);
        // Scroll after a brief delay to allow render
        setTimeout(() => {
          cardRefs.current[hash]?.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }, 100);
      } else {
        setHighlightedId(null);
      }
    }
    handleHash();
    window.addEventListener('hashchange', handleHash);
    return () => window.removeEventListener('hashchange', handleHash);
  }, []);

  return (
    <div className="flex-1 overflow-y-auto bg-warm-50 dark:bg-navy-950 flex flex-col">
      <div className="flex-1">
        <div className="max-w-5xl mx-auto px-6 py-8">
          <h1 className="text-2xl font-bold text-warm-900 dark:text-warm-100 mb-2">Data Sources</h1>
          <p className="text-warm-600 dark:text-warm-400 mb-6">
            This application combines {DATA_SOURCES.length} open datasets covering property prices,
            energy performance, transport, demographics, crime, environment, and more.
          </p>
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
            {DATA_SOURCES.map((source) => (
              <div
                key={source.id}
                id={source.id}
                ref={(el) => {
                  cardRefs.current[source.id] = el;
                }}
                className={`bg-white dark:bg-navy-800 rounded-lg border p-5 ${
                  highlightedId === source.id
                    ? 'border-teal-400 ring-2 ring-teal-400'
                    : 'border-warm-200 dark:border-navy-700'
                }`}
              >
                <div className="flex items-start justify-between gap-4 mb-2">
                  <h2 className="text-lg font-semibold text-warm-900 dark:text-warm-100">
                    {source.name}
                  </h2>
                  <span className="shrink-0 text-xs bg-warm-100 dark:bg-navy-700 text-warm-600 dark:text-warm-300 px-2 py-1 rounded">
                    {source.license}
                  </span>
                </div>
                <p className="text-sm text-warm-500 dark:text-warm-400 mb-2">
                  Source: {source.origin}
                </p>
                <p className="text-sm text-warm-700 dark:text-warm-300 mb-3">{source.use}</p>
                <a
                  href={source.url}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-sm text-teal-600 dark:text-teal-400 hover:text-teal-800 dark:hover:text-teal-300 hover:underline break-all"
                >
                  {source.url}
                </a>
              </div>
            ))}
          </div>
        </div>
      </div>

      <footer className="bg-navy-900 text-warm-400 px-6 py-6">
        <div className="max-w-5xl mx-auto">
          <h2 className="text-sm font-semibold text-warm-300 uppercase tracking-wide mb-3">
            Attribution
          </h2>
          <ul className="space-y-1.5 text-sm">
            <li>Contains HM Land Registry data &copy; Crown copyright and database right 2025.</li>
            <li>
              Contains public sector information licensed under the{' '}
              <a
                href="https://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/"
                target="_blank"
                rel="noopener noreferrer"
                className="text-teal-400 hover:text-teal-300 hover:underline"
              >
                Open Government Licence v3.0
              </a>
              .
            </li>
            <li>Contains OS data &copy; Crown copyright and database rights 2025.</li>
            <li>Powered by TfL Open Data.</li>
            <li>
              Contains data from{' '}
              <a
                href="https://www.openstreetmap.org/copyright"
                target="_blank"
                rel="noopener noreferrer"
                className="text-teal-400 hover:text-teal-300 hover:underline"
              >
                &copy; OpenStreetMap contributors
              </a>
              , available under the{' '}
              <a
                href="https://opendatacommons.org/licenses/odbl/"
                target="_blank"
                rel="noopener noreferrer"
                className="text-teal-400 hover:text-teal-300 hover:underline"
              >
                Open Data Commons Open Database License (ODbL)
              </a>
              .
            </li>
          </ul>
        </div>
      </footer>
    </div>
  );
}
