// ============================================================
// FACILITIES MAP — interactive
// Single-screen app-like experience. Click a facility for
// details; filter by type & state; search.
// ============================================================

function FacilitiesMap({ onBack, onNavigate }) {
  const [selectedId, setSelectedId] = React.useState('berkeley');
  const [typeFilter, setTypeFilter] = React.useState('all');
  const [query, setQuery] = React.useState('');
  const [hover, setHover] = React.useState(null);

  const filtered = FACILITIES.filter(f => {
    if (typeFilter === 'mine' && !f.type.includes('Mine')) return false;
    if (typeFilter === 'plant' && f.type === 'Headquarters') return false;
    if (typeFilter === 'plant' && f.type.includes('Mine') && f.type !== 'Mine + Plant') return false;
    if (typeFilter === 'hq' && f.type !== 'Headquarters') return false;
    if (query && !`${f.name} ${f.state}`.toLowerCase().includes(query.toLowerCase())) return false;
    return true;
  });

  const sel = FACILITIES.find(f => f.id === selectedId);

  return (
    <div className="dir-b ab-page" style={{ display: 'flex', flexDirection: 'column' }}>
      <BrowserChrome url="ussilica.com/about/facilities" />
      <NavB onNavigate={onNavigate} />
      <div className="fmap-grid" style={{ flex: 1, display: 'grid', gridTemplateColumns: '320px 1fr 380px', height: 'calc(900px - 36px - 60px)', overflow: 'hidden', background: 'var(--bg)' }}>
        {/* Left rail — filters + list */}
        <aside style={{ borderRight: '1px solid var(--line)', display: 'flex', flexDirection: 'column', background: 'var(--paper)' }}>
          <div style={{ padding: '22px 22px 14px' }}>
            <button onClick={onBack} style={{ background: 'transparent', border: 0, color: 'var(--ink-soft)', fontSize: 12, display: 'flex', alignItems: 'center', gap: 6 }}>
              <span style={{ transform: 'rotate(180deg)' }}><Icon.arrow size={12}/></span> Back to home
            </button>
            <h1 className="display" style={{ fontSize: 30, margin: '14px 0 4px', fontWeight: 500 }}>Network</h1>
            <p style={{ fontSize: 13, color: 'var(--ink-soft)', margin: 0 }}>27 facilities · 13 states</p>
            <div style={{ marginTop: 16, display: 'flex', alignItems: 'center', gap: 8, padding: '8px 12px', background: 'var(--bg)', borderRadius: 8, border: '1px solid var(--line)' }}>
              <Icon.search size={14}/>
              <input value={query} onChange={e => setQuery(e.target.value)} placeholder="Search by name or state"
                style={{ background: 'transparent', border: 0, outline: 'none', fontSize: 13, fontFamily: 'IBM Plex Sans', flex: 1, color: 'var(--ink)' }} />
            </div>
            <div style={{ marginTop: 14, display: 'flex', gap: 4 }}>
              {[['all', 'All'], ['mine', 'Mines'], ['plant', 'Plants'], ['hq', 'HQ']].map(([k, l]) => (
                <button key={k} onClick={() => setTypeFilter(k)} style={{
                  flex: 1, padding: '7px 8px', borderRadius: 6, fontSize: 12, fontWeight: 500,
                  border: '1px solid', borderColor: typeFilter === k ? 'var(--accent)' : 'var(--line)',
                  background: typeFilter === k ? 'var(--accent-soft)' : 'transparent',
                  color: typeFilter === k ? 'var(--accent)' : 'var(--ink-soft)',
                  cursor: 'pointer', transition: 'all .1s',
                }}>{l}</button>
              ))}
            </div>
          </div>
          <div style={{ overflowY: 'auto', flex: 1, padding: '0 12px 22px' }}>
            <div className="label-mono" style={{ padding: '10px 10px', color: 'var(--ink-soft)' }}>
              {filtered.length} OF {FACILITIES.length}
            </div>
            {filtered.map(f => (
              <div key={f.id} onClick={() => setSelectedId(f.id)}
                onMouseEnter={() => setHover(f.id)}
                onMouseLeave={() => setHover(null)}
                style={{
                  padding: '12px 12px', borderRadius: 8, cursor: 'pointer',
                  background: selectedId === f.id ? 'var(--accent-soft)' : (hover === f.id ? 'var(--bg)' : 'transparent'),
                  transition: 'background .1s', marginBottom: 2,
                  display: 'flex', alignItems: 'center', gap: 12,
                }}>
                <div style={{
                  width: 8, height: 8, borderRadius: 99,
                  background: f.type === 'Headquarters' ? 'var(--ink)' : (f.type.includes('Mine') ? 'var(--accent)' : 'oklch(0.7 0.12 252)'),
                }}/>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14, fontWeight: 500, color: selectedId === f.id ? 'var(--accent)' : 'var(--ink)' }}>{f.name}, {f.state}</div>
                  <div className="mono" style={{ fontSize: 11, color: 'var(--ink-soft)', marginTop: 2 }}>{f.type}</div>
                </div>
                {selectedId === f.id && <Icon.arrow size={13}/>}
              </div>
            ))}
          </div>
        </aside>

        {/* Map */}
        <main style={{ position: 'relative', overflow: 'hidden', background: 'var(--bg)' }}>
          <FacilitiesSVGMap selectedId={selectedId} setSelectedId={setSelectedId} hoverId={hover} setHover={setHover} filtered={filtered}/>
          {/* Legend */}
          <div style={{ position: 'absolute', bottom: 24, left: 24, background: 'var(--paper)', border: '1px solid var(--line)', borderRadius: 10, padding: 16, fontSize: 12, boxShadow: '0 8px 24px rgba(0,0,0,0.05)' }}>
            <div className="label-mono" style={{ marginBottom: 10 }}>LEGEND</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <span style={{ width: 12, height: 12, borderRadius: 99, background: 'var(--accent)' }}/>
                Mine + Plant
              </span>
              <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <span style={{ width: 12, height: 12, borderRadius: 99, background: 'oklch(0.7 0.12 252)' }}/>
                Plant only
              </span>
              <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <span style={{ width: 12, height: 12, borderRadius: 99, background: 'var(--ink)' }}/>
                Headquarters
              </span>
            </div>
          </div>
          {/* Scale */}
          <div style={{ position: 'absolute', top: 24, right: 24, fontFamily: 'IBM Plex Mono', fontSize: 11, color: 'var(--ink-soft)', display: 'flex', flexDirection: 'column', gap: 10, alignItems: 'flex-end' }}>
            <div>SCALE · 1:14,500,000</div>
            <div style={{ width: 80, height: 1, background: 'var(--ink-soft)', position: 'relative' }}>
              <div style={{ position: 'absolute', left: 0, top: -4, width: 1, height: 8, background: 'var(--ink-soft)' }}/>
              <div style={{ position: 'absolute', right: 0, top: -4, width: 1, height: 8, background: 'var(--ink-soft)' }}/>
            </div>
            <div>500 mi</div>
          </div>
        </main>

        {/* Right detail panel */}
        <aside style={{ borderLeft: '1px solid var(--line)', background: 'var(--paper)', overflowY: 'auto' }}>
          {sel && <FacilityDetail facility={sel} onNavigate={onNavigate}/>}
        </aside>
      </div>
    </div>
  );
}

function FacilitiesSVGMap({ selectedId, setSelectedId, hoverId, setHover, filtered }) {
  const filteredIds = new Set(filtered.map(f => f.id));
  return (
    <svg viewBox="0 0 900 460" style={{ width: '100%', height: '100%', display: 'block' }}>
      <defs>
        <pattern id="grid-fmap" width="30" height="30" patternUnits="userSpaceOnUse">
          <path d="M 30 0 L 0 0 0 30" fill="none" stroke="rgba(10,10,10,0.05)" strokeWidth="1"/>
        </pattern>
      </defs>
      <rect width="900" height="460" fill="url(#grid-fmap)"/>
      {/* US silhouette */}
      <path d={US_MAP_D} fill="oklch(0.96 0 0)" stroke="rgba(10,10,10,0.45)" strokeWidth="1.2"/>
      {/* State abbreviations */}
      {STATE_MARKS.map((s, i) => (
        <text key={i} x={s.x} y={s.y} fontSize="9" fontFamily="IBM Plex Mono" fill="rgba(10,10,10,0.32)" textAnchor="middle">{s.label}</text>
      ))}
      {/* Facility dots */}
      {FACILITIES.map(f => {
        const dim = !filteredIds.has(f.id);
        const isSel = selectedId === f.id;
        const isHover = hoverId === f.id;
        const color = f.type === 'Headquarters' ? '#0a0a0a' : (f.type.includes('Mine') ? 'oklch(0.48 0.18 252)' : 'oklch(0.7 0.12 252)');
        return (
          <g key={f.id}
            transform={`translate(${f.x * 9} ${f.y * 4.6})`}
            onClick={() => setSelectedId(f.id)}
            onMouseEnter={() => setHover(f.id)}
            onMouseLeave={() => setHover(null)}
            style={{ cursor: 'pointer', opacity: dim ? 0.18 : 1, transition: 'opacity .15s' }}>
            {(isSel || isHover) && <circle r="16" fill={color} opacity="0.18"/>}
            {isSel && <circle r="22" fill="none" stroke={color} strokeWidth="1" opacity="0.5"/>}
            <circle r={isSel ? 7 : 5} fill={color}/>
            {(isSel || isHover) && (
              <g transform="translate(12 4)">
                <rect x="-2" y="-12" width={f.name.length * 6.6 + f.state.length * 6.6 + 22} height="18" fill="var(--ink)" rx="3"/>
                <text x="6" y="0" fontSize="10" fontFamily="IBM Plex Mono" fill="white">{f.name}, {f.state}</text>
              </g>
            )}
          </g>
        );
      })}
      {/* Routes — visual flair, suggesting rail/truck connections */}
      {selectedId && (() => {
        const s = FACILITIES.find(x => x.id === selectedId);
        if (!s) return null;
        return FACILITIES.filter(f => f.id !== selectedId && f.type !== 'Headquarters').slice(0, 4).map((f, i) => (
          <line key={f.id}
            x1={s.x * 9} y1={s.y * 4.6} x2={f.x * 9} y2={f.y * 4.6}
            stroke="oklch(0.48 0.18 252)" strokeWidth="0.7" strokeDasharray="3 3" opacity="0.4"/>
        ));
      })()}
    </svg>
  );
}

function FacilityDetail({ facility, onNavigate }) {
  return (
    <div style={{ padding: 24, display: 'flex', flexDirection: 'column' }}>
      <div className="label-mono" style={{ marginBottom: 10, color: 'var(--accent)' }}>
        {facility.type.toUpperCase()}
      </div>
      <h2 className="display" style={{ fontSize: 32, margin: '0 0 6px', fontWeight: 500 }}>{facility.name}, {facility.state}</h2>
      <div className="mono" style={{ fontSize: 12, color: 'var(--ink-soft)' }}>
        ID · {facility.id.toUpperCase()} · LAT 39.6°N · LON 78.2°W
      </div>
      <div style={{ aspectRatio: '4 / 3', borderRadius: 8, overflow: 'hidden', marginTop: 18, background: '#000' }}>
        <Photo src="assets/facility-aerial.jpg" height="100%" />
      </div>
      <div style={{ marginTop: 18, padding: 18, background: 'var(--bg)', borderRadius: 10, border: '1px solid var(--line)' }}>
        <div className="label-mono" style={{ marginBottom: 12 }}>SITE PROFILE</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10, fontSize: 13 }}>
          {[
            ['Type', facility.type],
            ['Capacity', facility.capacity === 'HQ' ? '—' : `${facility.capacity} (${facility.capacity === 'High' ? '> 800k t/yr' : '300–800k t/yr'})`],
            ['Rail access', facility.id === 'frederick' ? 'No' : 'CSX / NS · Yes'],
            ['Truck dispatch', '24/7 · 6 doors'],
            ['ISO 9001', 'Certified'],
            ['On-site lab', facility.type.includes('Mine') ? 'Full (XRF, sieve, ICP)' : 'Sample retention'],
          ].map(([k, v]) => (
            <div key={k} style={{ display: 'flex', justifyContent: 'space-between' }}>
              <span style={{ color: 'var(--ink-soft)' }}>{k}</span>
              <span className="mono" style={{ fontWeight: 500 }}>{v}</span>
            </div>
          ))}
        </div>
      </div>
      {facility.products.length > 0 && (
        <div style={{ marginTop: 18 }}>
          <div className="label-mono" style={{ marginBottom: 10 }}>PRODUCING NOW</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {facility.products.map(sku => {
              const p = PRODUCTS.find(pp => pp.sku === sku);
              if (!p) return null;
              return (
                <div key={sku} onClick={() => onNavigate?.('product')} style={{
                  display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                  padding: 12, background: 'var(--bg)', borderRadius: 8, cursor: 'pointer',
                  border: '1px solid var(--line)',
                }}>
                  <div>
                    <div className="mono" style={{ fontSize: 11, color: 'var(--accent)' }}>{p.sku}</div>
                    <div style={{ fontSize: 13, fontWeight: 500, marginTop: 2 }}>{p.name}</div>
                  </div>
                  <Icon.arrow size={13}/>
                </div>
              );
            })}
          </div>
        </div>
      )}
      <button onClick={() => onNavigate?.('rfq')} style={{
        marginTop: 18, padding: '14px 18px', background: 'var(--ink)', color: 'var(--paper)',
        border: 0, borderRadius: 8, fontSize: 14, fontWeight: 500, cursor: 'pointer',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      }}>
        Request from this site <Icon.arrow size={13}/>
      </button>
    </div>
  );
}

Object.assign(window, { FacilitiesMap });
