// Burger House — Locations page (interactive map, postcode search, branch grid)

const BRANCHES = [
  {
    id: 'bristol-clifton',
    name: 'Bristol — Clifton',
    address: '24 Whiteladies Road, Clifton, Bristol BS8 2NB',
    postcode: 'BS8 2NB',
    phone: '+44 117 974 0001',
    lat: 51.4621, lng: -2.6116,
    hours: 'Mon–Sun · 11:00 – 22:30',
    features: ['Dine-in', 'Click & collect', 'Delivery', 'Drive-thru'],
    manager: 'Eleanor Hartley',
    openedYear: 2014,
    flagship: true,
  },
  {
    id: 'london-shoreditch',
    name: 'London — Shoreditch',
    address: '88 Curtain Road, Shoreditch, London EC2A 3AA',
    postcode: 'EC2A 3AA',
    phone: '+44 20 7613 0002',
    lat: 51.5252, lng: -0.0801,
    hours: 'Mon–Sun · 11:00 – 23:30',
    features: ['Dine-in', 'Late night', 'Click & collect', 'Delivery'],
    manager: 'Marcus Adeyemi',
    openedYear: 2017,
  },
  {
    id: 'london-soho',
    name: 'London — Soho',
    address: '12 Berwick Street, Soho, London W1F 0PN',
    postcode: 'W1F 0PN',
    phone: '+44 20 7437 0003',
    lat: 51.5135, lng: -0.1359,
    hours: 'Mon–Sun · 11:00 – 23:30',
    features: ['Dine-in', 'Late night', 'Click & collect', 'Delivery'],
    manager: 'Priya Shah',
    openedYear: 2019,
  },
  {
    id: 'manchester-nq',
    name: 'Manchester — Northern Quarter',
    address: '47 Tib Street, Northern Quarter, Manchester M4 1LX',
    postcode: 'M4 1LX',
    phone: '+44 161 832 0004',
    lat: 53.4837, lng: -2.2360,
    hours: 'Mon–Sun · 11:00 – 23:00',
    features: ['Dine-in', 'Click & collect', 'Delivery', 'Outdoor seating'],
    manager: 'Joe Whitaker',
    openedYear: 2020,
  },
  {
    id: 'edinburgh-old-town',
    name: 'Edinburgh — Old Town',
    address: '21 Cockburn Street, Old Town, Edinburgh EH1 1BP',
    postcode: 'EH1 1BP',
    phone: '+44 131 226 0005',
    lat: 55.9509, lng: -3.1900,
    hours: 'Mon–Sun · 11:00 – 22:00',
    features: ['Dine-in', 'Click & collect', 'Delivery'],
    manager: 'Cara MacLeod',
    openedYear: 2021,
  },
  {
    id: 'cardiff-city',
    name: 'Cardiff — City Centre',
    address: '6 Mill Lane, Cardiff CF10 1FL',
    postcode: 'CF10 1FL',
    phone: '+44 29 2034 0006',
    lat: 51.4791, lng: -3.1782,
    hours: 'Mon–Sun · 11:00 – 22:30',
    features: ['Dine-in', 'Click & collect', 'Delivery', 'Drive-thru'],
    manager: 'Owen Davies',
    openedYear: 2023,
    newest: true,
  },
];

// Approximate UK postcode area centroids (just enough to demo a "find nearest" flow without a network call).
const POSTCODE_AREAS = {
  BS: { lat: 51.4545, lng: -2.5879 },
  EC: { lat: 51.5179, lng: -0.0901 },
  W:  { lat: 51.5149, lng: -0.1564 },
  WC: { lat: 51.5174, lng: -0.1240 },
  N:  { lat: 51.5640, lng: -0.1100 },
  E:  { lat: 51.5400, lng: -0.0500 },
  SE: { lat: 51.4750, lng: -0.0500 },
  SW: { lat: 51.4700, lng: -0.1700 },
  NW: { lat: 51.5400, lng: -0.2000 },
  M:  { lat: 53.4808, lng: -2.2426 },
  EH: { lat: 55.9533, lng: -3.1883 },
  CF: { lat: 51.4816, lng: -3.1791 },
  B:  { lat: 52.4862, lng: -1.8904 },
  L:  { lat: 53.4084, lng: -2.9916 },
  LS: { lat: 53.8008, lng: -1.5491 },
  G:  { lat: 55.8642, lng: -4.2518 },
  S:  { lat: 53.3811, lng: -1.4701 },
  NE: { lat: 54.9783, lng: -1.6178 },
  BT: { lat: 54.5973, lng: -5.9301 },
};

const haversineKm = (a, b) => {
  const R = 6371;
  const toRad = d => d * Math.PI / 180;
  const dLat = toRad(b.lat - a.lat);
  const dLng = toRad(b.lng - a.lng);
  const lat1 = toRad(a.lat), lat2 = toRad(b.lat);
  const x = Math.sin(dLat / 2) ** 2 + Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLng / 2) ** 2;
  return 2 * R * Math.asin(Math.sqrt(x));
};

const lookupPostcode = (raw) => {
  if (!raw) return null;
  const cleaned = raw.toUpperCase().replace(/\s+/g, '');
  const exact = BRANCHES.find(b => b.postcode.replace(/\s+/g, '') === cleaned);
  if (exact) return { lat: exact.lat, lng: exact.lng, label: exact.postcode };
  const m = cleaned.match(/^([A-Z]{1,2})\d/);
  if (!m) return null;
  const area = POSTCODE_AREAS[m[1]];
  if (!area) return null;
  return { ...area, label: m[1] };
};

// Lazy-load Leaflet from CDN once.
let leafletPromise = null;
const ensureLeaflet = () => {
  if (typeof window === 'undefined') return Promise.resolve(null);
  if (window.L) return Promise.resolve(window.L);
  if (leafletPromise) return leafletPromise;
  leafletPromise = new Promise((resolve, reject) => {
    const css = document.createElement('link');
    css.rel = 'stylesheet';
    css.href = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css';
    document.head.appendChild(css);
    const s = document.createElement('script');
    s.src = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.js';
    s.onload = () => resolve(window.L);
    s.onerror = reject;
    document.head.appendChild(s);
  });
  return leafletPromise;
};

const BranchMap = ({ branches, selectedId, onSelect, focus }) => {
  const ref = React.useRef(null);
  const mapRef = React.useRef(null);
  const markersRef = React.useRef({});

  React.useEffect(() => {
    let cancelled = false;
    ensureLeaflet().then(L => {
      if (cancelled || !ref.current || mapRef.current) return;
      const map = L.map(ref.current, { scrollWheelZoom: false, zoomControl: true }).setView([54.5, -3], 5.4);
      L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; OpenStreetMap',
        maxZoom: 19,
      }).addTo(map);

      const accent = getComputedStyle(document.documentElement).getPropertyValue('--accent').trim() || '#c1410f';
      const ink = getComputedStyle(document.documentElement).getPropertyValue('--ink').trim() || '#1a1714';

      branches.forEach(b => {
        const html = `
          <div style="position:relative;width:34px;height:42px;">
            <div style="position:absolute;inset:0;background:${accent};border-radius:50% 50% 50% 0;transform:rotate(-45deg);box-shadow:0 6px 16px -4px rgba(0,0,0,.35);border:2px solid #fff;"></div>
            <div style="position:absolute;top:9px;left:9px;width:16px;height:16px;border-radius:50%;background:#fff;color:${ink};display:flex;align-items:center;justify-content:center;font:700 10px 'Inter Tight',sans-serif;">${b.name.charAt(0)}</div>
          </div>`;
        const icon = L.divIcon({ className: 'bh-pin', html, iconSize: [34, 42], iconAnchor: [17, 40], popupAnchor: [0, -36] });
        const m = L.marker([b.lat, b.lng], { icon }).addTo(map);
        m.bindPopup(`
          <div style="font-family:'Inter Tight',sans-serif;min-width:180px;">
            <div style="font-weight:600;font-size:14px;color:${ink};">${b.name}</div>
            <div style="font-size:12px;color:#666;margin-top:2px;">${b.address}</div>
            <div style="font-size:11px;color:${accent};margin-top:6px;font-family:'JetBrains Mono',monospace;">${b.hours}</div>
          </div>`);
        m.on('click', () => onSelect?.(b.id));
        markersRef.current[b.id] = m;
      });

      mapRef.current = map;
    });
    return () => { cancelled = true; };
  }, []);

  React.useEffect(() => {
    if (!mapRef.current || !selectedId) return;
    const b = branches.find(x => x.id === selectedId);
    if (!b) return;
    mapRef.current.flyTo([b.lat, b.lng], 13, { duration: 0.8 });
    const m = markersRef.current[b.id];
    if (m) m.openPopup();
  }, [selectedId, branches]);

  React.useEffect(() => {
    if (!mapRef.current || !focus) return;
    mapRef.current.flyTo([focus.lat, focus.lng], 11, { duration: 0.8 });
  }, [focus]);

  return <div ref={ref} className="bh-map" style={{ width: '100%', height: '100%', borderRadius: 20, overflow: 'hidden' }} />;
};

const FeatureChip = ({ children }) => (
  <span className="pill" style={{ height: 24, padding: '0 10px', fontSize: 11, background: 'var(--surface-2)', borderColor: 'transparent' }}>{children}</span>
);

const BranchCard = ({ b, distance, selected, onSelect }) => (
  <article
    onClick={onSelect}
    className="lift"
    style={{
      background: selected ? 'var(--accent-soft)' : 'var(--surface)',
      border: `1px solid ${selected ? 'var(--accent)' : 'var(--line)'}`,
      borderRadius: 18,
      padding: 18,
      cursor: 'pointer',
      display: 'flex',
      flexDirection: 'column',
      gap: 10,
    }}
  >
    <div className="row between" style={{ alignItems: 'flex-start' }}>
      <div className="col" style={{ gap: 4, minWidth: 0 }}>
        <div className="row gap-8" style={{ alignItems: 'center' }}>
          <h3 style={{ margin: 0, fontSize: 16, fontWeight: 600, letterSpacing: '-0.01em' }}>{b.name}</h3>
          {b.flagship && <span className="pill accent" style={{ height: 20, padding: '0 8px', fontSize: 10 }}>Flagship</span>}
          {b.newest && <span className="pill" style={{ height: 20, padding: '0 8px', fontSize: 10, background: 'var(--ink)', color: 'var(--bg)', borderColor: 'transparent' }}>New</span>}
        </div>
        <span className="muted" style={{ fontSize: 13, lineHeight: 1.4 }}>{b.address}</span>
      </div>
      {distance != null && (
        <div className="col" style={{ alignItems: 'flex-end', flexShrink: 0, marginLeft: 12 }}>
          <span className="display" style={{ fontSize: 22 }}>{distance.toFixed(1)}</span>
          <span className="mono" style={{ fontSize: 10, color: 'var(--ink-3)' }}>KM AWAY</span>
        </div>
      )}
    </div>
    <div className="row gap-8" style={{ flexWrap: 'wrap' }}>
      {b.features.map(f => <FeatureChip key={f}>{f}</FeatureChip>)}
    </div>
    <div className="row between" style={{ marginTop: 4, paddingTop: 10, borderTop: '1px solid var(--line)' }}>
      <span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>{b.hours}</span>
      <a href={`tel:${b.phone.replace(/\s/g, '')}`} onClick={e => e.stopPropagation()} className="mono" style={{ fontSize: 11, color: 'var(--accent)' }}>{b.phone}</a>
    </div>
  </article>
);

const LocationsPage = () => {
  const [query, setQuery] = React.useState('');
  const [origin, setOrigin] = React.useState(null);
  const [selectedId, setSelectedId] = React.useState(null);
  const [filter, setFilter] = React.useState('All');
  const [error, setError] = React.useState('');
  const inputRef = React.useRef(null);

  const search = (e) => {
    e?.preventDefault();
    const found = lookupPostcode(query);
    if (!found) { setError(query ? `We couldn't recognise "${query}". Try a UK postcode area like BS8 or M4.` : ''); setOrigin(null); return; }
    setError('');
    setOrigin(found);
  };

  const useMyLocation = () => {
    if (!navigator.geolocation) { setError('Geolocation not available in this browser.'); return; }
    setError('');
    navigator.geolocation.getCurrentPosition(
      pos => { setOrigin({ lat: pos.coords.latitude, lng: pos.coords.longitude, label: 'You' }); setQuery(''); },
      () => setError('Could not get your location. Allow location access or enter a postcode.'),
    );
  };

  const filtered = React.useMemo(() => {
    if (filter === 'All') return BRANCHES;
    return BRANCHES.filter(b => b.features.includes(filter));
  }, [filter]);

  const ranked = React.useMemo(() => {
    if (!origin) return filtered;
    return [...filtered]
      .map(b => ({ ...b, _d: haversineKm(origin, b) }))
      .sort((a, b) => a._d - b._d);
  }, [filtered, origin]);

  const filters = ['All', 'Drive-thru', 'Late night', 'Outdoor seating', 'Click & collect'];

  return (
    <>
      {/* Hero */}
      <section style={{ padding: '48px 0 24px' }}>
        <div className="container">
          <span className="eyebrow">Locations</span>
          <h1 className="display" style={{ fontSize: 'clamp(40px, 5vw, 72px)', margin: '14px 0 14px', lineHeight: 1.05 }}>
            Six kitchens.<br/>One <em style={{ color: 'var(--accent)' }}>standard</em>.
          </h1>
          <p style={{ fontSize: 17, color: 'var(--ink-2)', maxWidth: 560, margin: 0 }}>
            Find your nearest Burger House. Same beef, same buns, same sauce — in every city we serve.
          </p>
        </div>
      </section>

      {/* Search & filters */}
      <section style={{ padding: '16px 0' }}>
        <div className="container">
          <div className="card" style={{ padding: 18, display: 'flex', flexDirection: 'column', gap: 14 }}>
            <form className="row gap-12 locations-search" onSubmit={search} style={{ flexWrap: 'wrap' }}>
              <div className="row" style={{ flex: 1, minWidth: 240, alignItems: 'center', gap: 8, padding: '0 14px', height: 48, background: 'var(--surface-2)', borderRadius: 12 }}>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="var(--ink-3)" strokeWidth="2">
                  <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/><circle cx="12" cy="10" r="3"/>
                </svg>
                <input
                  ref={inputRef}
                  value={query}
                  onChange={e => setQuery(e.target.value)}
                  placeholder="Enter a UK postcode (e.g. BS8, EC2A, M4)"
                  style={{ all: 'unset', flex: 1, fontSize: 15, color: 'var(--ink)' }}
                  aria-label="Search by postcode"
                />
                {query && (
                  <button type="button" onClick={() => { setQuery(''); setOrigin(null); setError(''); inputRef.current?.focus(); }} style={{ all: 'unset', cursor: 'pointer', color: 'var(--ink-3)', fontSize: 13 }}>Clear</button>
                )}
              </div>
              <button type="submit" className="btn btn-primary" style={{ height: 48 }}>Find nearest</button>
              <button type="button" className="btn btn-ghost" onClick={useMyLocation} style={{ height: 48 }}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="3"/><path d="M12 2v3M12 19v3M2 12h3M19 12h3"/></svg>
                Use my location
              </button>
            </form>

            <div className="row gap-8" style={{ flexWrap: 'wrap' }}>
              {filters.map(f => (
                <button
                  key={f}
                  onClick={() => setFilter(f)}
                  style={{
                    all: 'unset', cursor: 'pointer',
                    padding: '6px 14px', borderRadius: 999, fontSize: 13,
                    background: filter === f ? 'var(--ink)' : 'var(--surface-2)',
                    color: filter === f ? 'var(--bg)' : 'var(--ink-2)',
                    border: '1px solid transparent',
                  }}>{f}</button>
              ))}
              <span className="mono" style={{ marginLeft: 'auto', fontSize: 11, color: 'var(--ink-3)', alignSelf: 'center' }}>
                {ranked.length} of {BRANCHES.length} branches
              </span>
            </div>

            {error && <div style={{ fontSize: 13, color: 'var(--accent)' }}>{error}</div>}
            {origin && !error && (
              <div className="mono" style={{ fontSize: 12, color: 'var(--ink-3)' }}>
                Showing branches nearest to <span style={{ color: 'var(--ink)' }}>{origin.label}</span>.
              </div>
            )}
          </div>
        </div>
      </section>

      {/* Map + branch list */}
      <section style={{ padding: '24px 0 64px' }}>
        <div className="container locations-grid" style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 20, alignItems: 'stretch' }}>
          <div style={{ minHeight: 560, height: '70vh', maxHeight: 720, position: 'sticky', top: 88, alignSelf: 'flex-start' }}>
            <BranchMap branches={BRANCHES} selectedId={selectedId} onSelect={setSelectedId} focus={origin} />
          </div>
          <div className="col gap-12" style={{ minWidth: 0 }}>
            {ranked.map(b => (
              <BranchCard
                key={b.id}
                b={b}
                distance={origin ? b._d : null}
                selected={selectedId === b.id}
                onSelect={() => setSelectedId(b.id)}
              />
            ))}
          </div>
        </div>
      </section>

      {/* Live ops strip */}
      <section style={{ padding: '24px 0 80px' }}>
        <div className="container">
          <div className="card" style={{ padding: 28, background: 'var(--ink)', color: 'var(--bg)', borderColor: 'transparent' }}>
            <div className="row between" style={{ flexWrap: 'wrap', gap: 24, alignItems: 'center' }}>
              <div>
                <span className="eyebrow" style={{ color: 'var(--ink-3)' }}>Live · Network</span>
                <h3 className="display" style={{ fontSize: 28, margin: '8px 0 0', color: 'var(--bg)' }}>What's happening across the network right now.</h3>
              </div>
              <div className="row gap-32" style={{ flexWrap: 'wrap' }}>
                {[
                  ['6', 'open kitchens'],
                  ['~14m', 'avg wait'],
                  ['1,284', 'orders today'],
                  ['98%', 'on-time pickups'],
                ].map(([n, l]) => (
                  <div key={l} className="col">
                    <span className="display" style={{ fontSize: 28, color: 'var(--bg)' }}>{n}</span>
                    <span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 4, textTransform: 'uppercase' }}>{l}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Franchise CTA */}
      <section style={{ padding: '0 0 80px' }}>
        <div className="container locations-cta" style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 24 }}>
          <div className="card" style={{ padding: 32, background: 'var(--accent-soft)', borderColor: 'transparent' }}>
            <span className="eyebrow" style={{ color: 'var(--accent)' }}>Franchise</span>
            <h3 className="display" style={{ fontSize: 32, margin: '12px 0 12px' }}>Open the next Burger House.</h3>
            <p style={{ color: 'var(--ink-2)', maxWidth: 460, margin: '0 0 20px' }}>
              We're partnering with operators in 12 UK cities. £180k average annual operator profit, 8-week build, full training programme.
            </p>
            <div className="row gap-12">
              <a className="btn btn-primary">Apply to franchise</a>
              <a className="btn btn-ghost">Download prospectus →</a>
            </div>
          </div>
          <div className="card" style={{ padding: 32 }}>
            <span className="eyebrow">Get in touch</span>
            <h3 className="display" style={{ fontSize: 24, margin: '12px 0 16px' }}>Branch enquiries</h3>
            <div className="col gap-12">
              <div><div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase' }}>Press</div><div style={{ fontSize: 14 }}>press@burgerhouse.co.uk</div></div>
              <div><div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase' }}>Bookings · 20+ guests</div><div style={{ fontSize: 14 }}>events@burgerhouse.co.uk</div></div>
              <div><div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase' }}>HQ</div><div style={{ fontSize: 14 }}>+44 117 974 0000</div></div>
            </div>
          </div>
        </div>
      </section>

      <Footer />
    </>
  );
};

Object.assign(window, { LocationsPage });
