// DirectoryMap.jsx, Suppliers by location variant of Directory

const DM_LOCATIONS = [
 { id: "hai-phong", city: "Hai Phong", cityJa: "ハイフォン", country: "vn", region: "vn-north", x: 232, y: 138, port: true },
 { id: "da-nang", city: "Da Nang", cityJa: "ダナン", country: "vn", region: "vn-central", x: 248, y: 288, port: true },
 { id: "ho-chi-minh", city: "Ho Chi Minh",cityJa: "ホーチミン", country: "vn", region: "vn-south", x: 198, y: 452, port: true },
 { id: "can-tho", city: "Can Tho", cityJa: "カントー", country: "vn", region: "vn-south", x: 168, y: 478, port: false },
 { id: "ca-mau", city: "Ca Mau", cityJa: "カマウ", country: "vn", region: "vn-south", x: 142, y: 510, port: true },
 { id: "sapporo", city: "Sapporo", cityJa: "札幌", country: "jp", region: "jp-hokkaido",x: 905, y: 122, port: true },
 { id: "tokyo", city: "Tokyo", cityJa: "東京", country: "jp", region: "jp-kanto", x: 905, y: 302, port: false },
 { id: "yokohama", city: "Yokohama", cityJa: "横浜", country: "jp", region: "jp-kanto", x: 895, y: 322, port: true },
 { id: "osaka", city: "Osaka", cityJa: "大阪", country: "jp", region: "jp-kansai", x: 808, y: 338, port: true },
];

const DM_REGIONS = [
 { id: "all", label: "All locations", ja: "すべて", country: null },
 { id: "vn-north", label: "Northern VN", ja: "北部", country: "vn" },
 { id: "vn-central", label: "Central VN", ja: "中部", country: "vn" },
 { id: "vn-south", label: "Southern VN", ja: "南部", country: "vn" },
 { id: "jp-hokkaido", label: "Hokkaido", ja: "北海道", country: "jp" },
 { id: "jp-kanto", label: "Kanto", ja: "関東", country: "jp" },
 { id: "jp-kansai", label: "Kansai", ja: "関西", country: "jp" },
];

const DM_LANES = [
 { id: "hp-yk", from: "hai-phong", to: "yokohama", label: "Hai Phong → Yokohama", transit: "4 days", weekly: 6 },
 { id: "hp-os", from: "hai-phong", to: "osaka", label: "Hai Phong → Osaka", transit: "5 days", weekly: 3 },
 { id: "hc-yk", from: "ho-chi-minh",to: "yokohama", label: "Ho Chi Minh → Yokohama", transit: "7 days", weekly: 4 },
 { id: "dn-os", from: "da-nang", to: "osaka", label: "Da Nang → Osaka", transit: "6 days", weekly: 2 },
];

const dmSuppliersByCity = (filterFn = () => true) => {
 const map = {};
 for (const s of SUPPLIERS) {
  if (!filterFn(s)) continue;
  (map[s.city] = map[s.city] || []).push(s);
 }
 return map;
};

const DirectoryMap = ({ onNavigate, onRFQ }) => {
 const vp = useViewport();
 const [country, setCountry] = useState("any");
 const [selectedRegion, setSelectedRegion] = useState("all");
 const [selectedCity, setSelectedCity] = useState(null);
 const [hoverCity, setHoverCity] = useState(null);
 const [highlightedRegion, setHighlightedRegion] = useState(null);
 const [verifiedOnly, setVerifiedOnly] = useState(true);

 const baseFilter = (s) => {
  if (verifiedOnly && !s.verified) return false;
  if (country !== "any" && s.country !== country) return false;
  return true;
 };

 const countsByCity = {};
 for (const s of SUPPLIERS) {
  if (!baseFilter(s)) continue;
  countsByCity[s.city] = (countsByCity[s.city] || 0) + 1;
 }
 const regionCount = (rid) => {
  if (rid === "all") return Object.values(countsByCity).reduce((a, b) => a + b, 0);
  const cities = DM_LOCATIONS.filter(l => l.region === rid).map(l => l.city);
  return cities.reduce((a, c) => a + (countsByCity[c] || 0), 0);
 };

 const filtered = SUPPLIERS.filter(s => {
  if (!baseFilter(s)) return false;
  if (selectedCity) {
   const loc = DM_LOCATIONS.find(l => l.id === selectedCity);
   return loc && s.city === loc.city;
  }
  if (selectedRegion !== "all") {
   const loc = DM_LOCATIONS.find(l => l.city === s.city);
   return loc && loc.region === selectedRegion;
  }
  return true;
 });

 const selectedLoc = selectedCity ? DM_LOCATIONS.find(l => l.id === selectedCity) : null;
 const selectedReg = selectedRegion !== "all" ? DM_REGIONS.find(r => r.id === selectedRegion) : null;

 const clearAll = () => { setSelectedCity(null); setSelectedRegion("all"); };

 const chipGroups = [
  { country: null, regions: ["all"] },
  { country: "vn", regions: DM_REGIONS.filter(r => r.country === "vn").map(r => r.id) },
  { country: "jp", regions: DM_REGIONS.filter(r => r.country === "jp").map(r => r.id) },
 ];

 return (
  <div>
   <section style={{ padding: "32px var(--pad-x) 24px", borderBottom: "1px solid var(--color-border)" }}>
    <div style={{ maxWidth: 1280, margin: "0 auto" }}>
     <div style={{ fontSize: 12, color: "var(--color-fg-muted)", display: "flex", gap: 6, marginBottom: 12, flexWrap: "wrap" }}>
      <a href="#" onClick={e => { e.preventDefault(); onNavigate("home"); }} style={{ color: "var(--color-fg-muted)", border: 0 }}>Home</a>
      <span>/</span>
      <a href="#" onClick={e => { e.preventDefault(); onNavigate("directory"); }} style={{ color: "var(--color-fg-muted)", border: 0 }}>Suppliers</a>
      <span>/</span><span style={{ color: "var(--color-fg)" }}>By location</span>
     </div>
     <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 24, flexWrap: "wrap" }}>
      <div style={{ minWidth: 0 }}>
       <Eyebrow style={{ marginBottom: 8 }}>Find by location</Eyebrow>
       <h1 style={{ fontSize: vp.isMobile ? 24 : 32, lineHeight: 1.2, letterSpacing: "-0.015em", color: "var(--jv-navy-800)", margin: 0 }}>
        Suppliers across the Vietnam ⇄ Japan corridor
       </h1>
       <div style={{ marginTop: 8, fontSize: 14, color: "var(--color-fg-muted)" }}>
        <Mono style={{ color: "var(--color-fg)" }}>{filtered.length}</Mono> verified suppliers across
        <Mono style={{ color: "var(--color-fg)", marginLeft: 6 }}>{Object.keys(countsByCity).length}</Mono> export hubs · weekly sailings to Yokohama, Osaka and Kobe
       </div>
      </div>
      <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
       <Button variant="ghost" size="sm" onClick={() => onNavigate("directory")}>Cards</Button>
       <Button variant="ghost" size="sm" onClick={() => onNavigate("directory")}>Table</Button>
       <Button variant="secondary" size="sm" leading="globe">Map</Button>
       <Button variant="primary" size="sm" onClick={onRFQ}>Post an RFQ</Button>
      </div>
     </div>
    </div>
   </section>

   <div style={{ maxWidth: 1280, margin: "0 auto", padding: "24px var(--pad-x) 0" }}>
    {/* REGION CHIPS + GLOBAL TOGGLES */}
    <div style={{
     display: "flex", alignItems: "center", justifyContent: "space-between",
     gap: 16, padding: "14px 16px",
     border: "1px solid var(--color-border)", borderRadius: 8, background: "var(--jv-ink-50)",
     marginBottom: 16, flexWrap: "wrap",
    }}>
     <div style={{ display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap" }}>
      <Eyebrow>Region</Eyebrow>
      {chipGroups.map((g, gi) => (
       <React.Fragment key={gi}>
        {gi > 0 && !vp.isMobile && <span style={{ width: 1, height: 18, background: "var(--color-border)" }}/>}
        {g.country && (
         <img src={`assets/flag-${g.country}.svg`} width="16" height="12" alt="" style={{ borderRadius: 2 }}/>
        )}
        {g.regions.map(rid => {
         const r = DM_REGIONS.find(x => x.id === rid);
         const active = selectedRegion === rid && !selectedCity;
         const count = regionCount(rid);
         return (
          <button key={rid}
           onClick={() => { setSelectedCity(null); setSelectedRegion(rid); }}
           onMouseEnter={() => setHighlightedRegion(rid)}
           onMouseLeave={() => setHighlightedRegion(null)}
           style={{
            display: "inline-flex", alignItems: "center", gap: 8,
            padding: "6px 12px",
            background: active ? "var(--jv-navy-800)" : "#fff",
            color: active ? "#fff" : "var(--jv-navy-800)",
            border: `1px solid ${active ? "var(--jv-navy-800)" : "var(--color-border)"}`,
            borderRadius: 999, fontSize: 13, fontWeight: 500,
            cursor: "pointer", fontFamily: "var(--font-sans)",
            transition: "background 120ms, border-color 120ms",
           }}>
           {r.label}
           <span style={{
            fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 600,
            padding: "1px 6px", borderRadius: 999,
            background: active ? "rgba(255,255,255,0.18)" : "var(--jv-ink-100)",
            color: active ? "#fff" : "var(--color-fg-muted)",
           }}>{count}</span>
          </button>
         );
        })}
       </React.Fragment>
      ))}
     </div>
     <label style={{ display: "inline-flex", alignItems: "center", gap: 8, fontSize: 13, color: "var(--color-fg-body)", whiteSpace: "nowrap" }}>
      <input type="checkbox" checked={verifiedOnly} onChange={e => setVerifiedOnly(e.target.checked)} style={{ accentColor: "var(--jv-navy-800)" }}/>
      Verified only
     </label>
    </div>

    {/* MAP + SIDE PANEL */}
    <div style={{ display: "grid", gridTemplateColumns: vp.isDesktop ? "1fr 340px" : "1fr", gap: 16, marginBottom: 24 }}>
     <div className={vp.isTabletDown ? "jv-x-scroll" : ""} style={vp.isTabletDown ? { borderRadius: 10, overflow: "auto", border: "1px solid var(--color-border)" } : {}}>
      <div style={vp.isTabletDown ? { minWidth: 720 } : {}}>
       <CorridorMap
        locations={DM_LOCATIONS}
        lanes={DM_LANES}
        countsByCity={countsByCity}
        selectedRegion={selectedRegion}
        selectedCity={selectedCity}
        hoverCity={hoverCity}
        highlightedRegion={highlightedRegion}
        onCityHover={setHoverCity}
        onCityClick={(id) => {
         setSelectedRegion("all");
         setSelectedCity(prev => prev === id ? null : id);
        }}
        onBackgroundClick={() => setSelectedCity(null)}
       />
      </div>
     </div>
     <LocationSummary
      selectedLoc={selectedLoc}
      selectedReg={selectedReg}
      countsByCity={countsByCity}
      filtered={filtered}
      onClear={clearAll}
      lanes={DM_LANES}
     />
    </div>

    {/* RESULTS */}
    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", margin: "12px 0 16px", gap: 12, flexWrap: "wrap" }}>
     <div style={{ fontSize: 14, color: "var(--color-fg-body)" }}>
      {selectedLoc ? (
       <span>Showing suppliers in <strong style={{ color: "var(--jv-navy-800)" }}>{selectedLoc.city}</strong></span>
      ) : selectedReg ? (
       <span>Showing suppliers in <strong style={{ color: "var(--jv-navy-800)" }}>{selectedReg.label}</strong></span>
      ) : (
       <span>Showing all <Mono style={{ color: "var(--color-fg)" }}>{filtered.length}</Mono> suppliers in the corridor</span>
      )}
     </div>
     <div style={{ display: "flex", gap: 8, alignItems: "center", fontSize: 13, color: "var(--color-fg-muted)" }}>
      Sort
      <Select defaultValue="proximity" style={{ width: 180 }}>
       <option value="proximity">Nearest port first</option>
       <option value="verified">Verification date</option>
       <option value="moq">Lowest MOQ</option>
       <option value="lead">Shortest lead time</option>
      </Select>
     </div>
    </div>

    <div style={{ display: "grid", gridTemplateColumns: vp.isMobile ? "1fr" : "repeat(auto-fill, minmax(280px, 1fr))", gap: 16 }}>
     {filtered.map(s => (
      <div key={s.id}
       onMouseEnter={() => {
        const loc = DM_LOCATIONS.find(l => l.city === s.city);
        if (loc) setHoverCity(loc.id);
       }}
       onMouseLeave={() => setHoverCity(null)}>
       <SupplierCard supplier={s} onClick={() => onNavigate("profile", s.id)} onRFQ={onRFQ}/>
      </div>
     ))}
     {filtered.length === 0 && (
      <div style={{ gridColumn: "1 / -1", padding: 40, textAlign: "center", border: "1px dashed var(--color-border)", borderRadius: 8, color: "var(--color-fg-muted)", fontSize: 14 }}>
       No suppliers match the current location filter.
       <Button variant="link" onClick={clearAll} style={{ marginLeft: 8 }}>Reset filters</Button>
      </div>
     )}
    </div>
   </div>
  </div>
 );
};

const LocationSummary = ({ selectedLoc, selectedReg, countsByCity, filtered, onClear, lanes }) => {
 if (!selectedLoc && !selectedReg) {
  const hubs = DM_LOCATIONS
   .map(l => ({ ...l, count: countsByCity[l.city] || 0 }))
   .filter(l => l.count > 0)
   .sort((a, b) => b.count - a.count);
  return (
   <aside style={{ background: "#fff", border: "1px solid var(--color-border)", borderRadius: 10, padding: 20, display: "flex", flexDirection: "column", gap: 16, boxSizing: "border-box" }}>
    <div>
     <Eyebrow>Corridor at a glance</Eyebrow>
     <div style={{ marginTop: 10, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
      <StatBlock value={filtered.length} label="Verified suppliers"/>
      <StatBlock value={hubs.length} label="Active hubs"/>
      <StatBlock value="15" suffix=" /wk" label="Sailings"/>
      <StatBlock value="3 600" suffix=" km" label="Avg. corridor"/>
     </div>
    </div>
    <div style={{ borderTop: "1px solid var(--color-divider)", paddingTop: 14 }}>
     <Eyebrow>Top hubs</Eyebrow>
     <div style={{ marginTop: 10, display: "flex", flexDirection: "column", gap: 8 }}>
      {hubs.slice(0, 5).map(h => (
       <div key={h.id} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", fontSize: 13 }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
         <img src={`assets/flag-${h.country}.svg`} width="14" height="11"/>
         <span style={{ color: "var(--jv-navy-800)", fontWeight: 500 }}>{h.city}</span>
        </span>
        <Mono style={{ color: "var(--color-fg-muted)" }}>{h.count}</Mono>
       </div>
      ))}
     </div>
    </div>
    <div style={{ marginTop: "auto", padding: 12, background: "var(--jv-sand-100)", border: "1px solid var(--jv-sand-200)", borderRadius: 8, fontSize: 12, color: "var(--jv-navy-800)", lineHeight: 1.5 }}>
     <strong style={{ display: "block", marginBottom: 4 }}>Tip</strong>
     Click any pin to focus a hub, or pick a region chip to filter the corridor.
    </div>
   </aside>
  );
 }

 if (selectedLoc) {
  const sups = filtered;
  const outboundLanes = lanes.filter(l => l.from === selectedLoc.id);
  const inboundLanes = lanes.filter(l => l.to === selectedLoc.id);
  const relevantLanes = [...outboundLanes, ...inboundLanes];
  return (
   <aside style={{ background: "#fff", border: "1px solid var(--color-border)", borderRadius: 10, padding: 20, display: "flex", flexDirection: "column", gap: 16, boxSizing: "border-box" }}>
    <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between" }}>
     <div>
      <div style={{ display: "inline-flex", alignItems: "center", gap: 8, marginBottom: 6 }}>
       <img src={`assets/flag-${selectedLoc.country}.svg`} width="18" height="14"/>
       {selectedLoc.port && <StatusPill tone="neutral">Sea port</StatusPill>}
      </div>
      <div style={{ fontSize: 20, fontWeight: 600, color: "var(--jv-navy-800)", lineHeight: 1.2 }}>{selectedLoc.city}</div>
     </div>
     <button onClick={onClear} aria-label="Clear" style={{ background: "transparent", border: 0, padding: 6, cursor: "pointer", color: "var(--color-fg-muted)" }}>
      <Icon name="x" size={18}/>
     </button>
    </div>
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
     <StatBlock value={sups.length} label="Suppliers here"/>
     <StatBlock value={relevantLanes.length} label="Trade lanes"/>
    </div>
    {relevantLanes.length > 0 && (
     <div style={{ borderTop: "1px solid var(--color-divider)", paddingTop: 14 }}>
      <Eyebrow>Active lanes</Eyebrow>
      <div style={{ marginTop: 10, display: "flex", flexDirection: "column", gap: 8 }}>
       {relevantLanes.map(ln => (
        <div key={ln.id} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", fontSize: 13, padding: "8px 10px", background: "var(--jv-ink-50)", borderRadius: 6, gap: 8, flexWrap: "wrap" }}>
         <span style={{ color: "var(--jv-navy-800)", fontWeight: 500 }}>{ln.label}</span>
         <span style={{ display: "inline-flex", gap: 10, color: "var(--color-fg-muted)", fontFamily: "var(--font-mono)", fontSize: 11 }}>
          <span>{ln.transit}</span>
          <span>{ln.weekly}×/wk</span>
         </span>
        </div>
       ))}
      </div>
     </div>
    )}
    <div style={{ marginTop: "auto", display: "flex", gap: 8, flexWrap: "wrap" }}>
     <Button variant="secondary" size="sm" onClick={onClear}>Reset</Button>
     <Button variant="primary" size="sm" trailing="arrow-right">RFQ from {selectedLoc.city}</Button>
    </div>
   </aside>
  );
 }

 const regionHubs = DM_LOCATIONS
  .filter(l => l.region === selectedReg.id)
  .map(l => ({ ...l, count: countsByCity[l.city] || 0 }));
 return (
  <aside style={{ background: "#fff", border: "1px solid var(--color-border)", borderRadius: 10, padding: 20, display: "flex", flexDirection: "column", gap: 16, boxSizing: "border-box" }}>
   <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between" }}>
    <div>
     <div style={{ display: "inline-flex", alignItems: "center", gap: 8, marginBottom: 6 }}>
      {selectedReg.country && <img src={`assets/flag-${selectedReg.country}.svg`} width="18" height="14"/>}
      <Eyebrow>Region</Eyebrow>
     </div>
     <div style={{ fontSize: 20, fontWeight: 600, color: "var(--jv-navy-800)", lineHeight: 1.2 }}>{selectedReg.label}</div>
    </div>
    <button onClick={onClear} aria-label="Clear" style={{ background: "transparent", border: 0, padding: 6, cursor: "pointer", color: "var(--color-fg-muted)" }}>
     <Icon name="x" size={18}/>
    </button>
   </div>
   <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
    <StatBlock value={filtered.length} label="Suppliers"/>
    <StatBlock value={regionHubs.filter(h => h.count > 0).length} label="Active hubs"/>
   </div>
   <div style={{ borderTop: "1px solid var(--color-divider)", paddingTop: 14 }}>
    <Eyebrow>Hubs in {selectedReg.label}</Eyebrow>
    <div style={{ marginTop: 10, display: "flex", flexDirection: "column", gap: 8 }}>
     {regionHubs.map(h => (
      <div key={h.id} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", fontSize: 13 }}>
       <span style={{ color: "var(--jv-navy-800)", fontWeight: 500 }}>
        {h.city}
       </span>
       <Mono style={{ color: "var(--color-fg-muted)" }}>{h.count}</Mono>
      </div>
     ))}
    </div>
   </div>
   <div style={{ marginTop: "auto" }}>
    <Button variant="secondary" size="sm" onClick={onClear}>Reset</Button>
   </div>
  </aside>
 );
};

const StatBlock = ({ value, suffix, label }) => (
 <div style={{ padding: "10px 12px", background: "var(--jv-ink-50)", borderRadius: 6 }}>
  <div style={{ fontFamily: "var(--font-mono)", fontWeight: 600, fontSize: 20, color: "var(--jv-navy-800)", lineHeight: 1.1 }}>
   {value}{suffix && <span style={{ fontSize: 13, color: "var(--color-fg-muted)" }}>{suffix}</span>}
  </div>
  <div style={{ marginTop: 4, fontSize: 11, color: "var(--color-fg-muted)", letterSpacing: "0.02em" }}>{label}</div>
 </div>
);

Object.assign(window, { DM_LOCATIONS, DM_REGIONS, DM_LANES, dmSuppliersByCity, DirectoryMap });
