// BranchSelector — selector inicial con geolocalización + selector manual + switcher en nav

function BranchSelector({ branches, onSelect, currentBranchId, mode = "initial" }) {
  // mode: "initial" (overlay completo, primera vez) | "switch" (modal compacto al cambiar)
  const [geoState, setGeoState] = React.useState("idle"); // idle | locating | suggested | denied | done
  const [suggested, setSuggested] = React.useState(null);
  const activeBranches = branches.filter(b => b.active);

  React.useEffect(() => {
    if (mode !== "initial") return;
    if (!navigator.geolocation) { setGeoState("denied"); return; }
    setGeoState("locating");
    navigator.geolocation.getCurrentPosition(
      pos => {
        const { latitude, longitude } = pos.coords;
        let best = null;
        for (const b of activeBranches) {
          if (typeof b.lat !== "number" || typeof b.lng !== "number") continue;
          const d = haversineKm(latitude, longitude, b.lat, b.lng);
          if (d <= 15 && (!best || d < best.dist)) best = { branch: b, dist: d };
        }
        if (best) { setSuggested(best); setGeoState("suggested"); }
        else setGeoState("denied");
      },
      err => setGeoState("denied"),
      { timeout: 7000, maximumAge: 60000 }
    );
  }, [mode]);

  const handleConfirm = (branchId) => onSelect(branchId);

  if (mode === "switch") {
    return (
      <div style={overlayStyle} onClick={() => onSelect(currentBranchId)}>
        <div style={{ ...sheetStyle, maxWidth: 440 }} onClick={e => e.stopPropagation()}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 18 }}>
            <h2 style={{ color: "#1a1008", fontFamily: "'Bebas Neue', cursive", fontSize: 24, letterSpacing: "0.04em", margin: 0 }}>
              Cambiar sucursal
            </h2>
            <button onClick={() => onSelect(currentBranchId)} style={{
              background: "#f5ede1", border: "none", color: "#6b5d4e",
              borderRadius: "50%", width: 32, height: 32, cursor: "pointer", fontSize: 14
            }}>✕</button>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {activeBranches.map(b => (
              <BranchOption key={b.id} branch={b} active={b.id === currentBranchId} onClick={() => handleConfirm(b.id)} />
            ))}
          </div>
        </div>
      </div>
    );
  }

  // Initial selector — full screen
  return (
    <div style={{
      position: "fixed", inset: 0, background: "#fdfaf3", zIndex: 9999,
      display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
      padding: 24, fontFamily: "'DM Sans', sans-serif"
    }}>
      <div style={{ maxWidth: 440, width: "100%", textAlign: "center" }}>
        <img src="assets/logo.png" alt="HLPRaf" style={{ height: 90, marginBottom: 16 }} />
        <h1 style={{ fontFamily: "'Bebas Neue', cursive", fontSize: 32, letterSpacing: "0.04em", color: "#1a1008", lineHeight: 1.05 }}>
          Hola, en qué sucursal estás?
        </h1>
        <p style={{ color: "#6b5d4e", fontSize: 14, marginTop: 6, marginBottom: 24 }}>
          Te mostramos el catálogo, precios y horarios del local que elijas.
        </p>

        {geoState === "locating" && (
          <div style={{
            background: "#fff", border: "1px solid #e8dcc8", borderRadius: 14,
            padding: 18, marginBottom: 16, display: "flex", alignItems: "center", gap: 12
          }}>
            <div style={{ fontSize: 24, animation: "pulseDot 1.5s ease-in-out infinite" }}>📍</div>
            <div style={{ textAlign: "left", flex: 1 }}>
              <div style={{ fontWeight: 700, color: "#1a1008", fontSize: 14 }}>Detectando tu ubicación...</div>
              <div style={{ color: "#8a7a66", fontSize: 12 }}>Buscamos la sucursal más cercana</div>
            </div>
          </div>
        )}

        {geoState === "suggested" && suggested && (
          <div style={{
            background: "linear-gradient(135deg, #fff7ed, #ffedd5)",
            border: "2px solid #d97706", borderRadius: 14,
            padding: 18, marginBottom: 16, textAlign: "left"
          }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
              <span style={{ fontSize: 18 }}>📍</span>
              <span style={{ fontSize: 11, fontWeight: 800, color: "#d97706", textTransform: "uppercase", letterSpacing: "0.06em" }}>
                Te queda cerca
              </span>
            </div>
            <div style={{ fontFamily: "'Bebas Neue', cursive", fontSize: 26, color: "#1a1008", letterSpacing: "0.03em" }}>
              {suggested.branch.name}
            </div>
            <div style={{ color: "#6b5d4e", fontSize: 13, marginBottom: 12 }}>
              {suggested.branch.address} · A {suggested.dist.toFixed(1)} km de tu ubicación
            </div>
            <button onClick={() => handleConfirm(suggested.branch.id)} style={{
              width: "100%", background: "#d97706", color: "#fff",
              border: "none", borderRadius: 12, padding: "13px 0",
              fontWeight: 800, fontSize: 15, cursor: "pointer", fontFamily: "'DM Sans', sans-serif"
            }}>Confirmar {suggested.branch.name}</button>
          </div>
        )}

        <div style={{ display: "flex", alignItems: "center", gap: 10, margin: "20px 0 14px", color: "#8a7a66", fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.08em" }}>
          <div style={{ flex: 1, height: 1, background: "#e8dcc8" }} />
          <span>{geoState === "suggested" ? "O elegí otra" : "Elegí tu sucursal"}</span>
          <div style={{ flex: 1, height: 1, background: "#e8dcc8" }} />
        </div>

        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          {activeBranches.map(b => (
            <BranchOption key={b.id} branch={b} onClick={() => handleConfirm(b.id)} />
          ))}
        </div>

        {branches.some(b => !b.active) && (
          <div style={{ marginTop: 14, fontSize: 11, color: "#a89882" }}>
            Otras sucursales próximamente: {branches.filter(b => !b.active).map(b => b.name).join(", ")}
          </div>
        )}
      </div>
      <style>{`@keyframes pulseDot { 0%, 100% { opacity: 1; transform: scale(1); } 50% { opacity: 0.5; transform: scale(0.85); } }`}</style>
    </div>
  );
}

function BranchOption({ branch, active, onClick }) {
  return (
    <button onClick={onClick} style={{
      display: "flex", alignItems: "center", gap: 12,
      background: active ? "#fdf3e1" : "#fff",
      border: active ? "2px solid #d97706" : "1.5px solid #e8dcc8",
      borderRadius: 12, padding: "14px 16px", cursor: "pointer",
      textAlign: "left", width: "100%", fontFamily: "'DM Sans', sans-serif",
      transition: "all 0.15s"
    }}>
      <div style={{
        background: "#fdf3e1", borderRadius: 10,
        width: 40, height: 40, display: "flex", alignItems: "center", justifyContent: "center",
        fontSize: 20, flexShrink: 0
      }}>📍</div>
      <div style={{ flex: 1 }}>
        <div style={{ fontWeight: 800, color: "#1a1008", fontSize: 15 }}>{branch.name}</div>
        <div style={{ fontSize: 11, color: "#8a7a66", lineHeight: 1.4 }}>
          {branch.address}{branch.hours ? ` · ${branch.hours}` : ""}
        </div>
      </div>
      {active && <div style={{ color: "#d97706", fontSize: 18, fontWeight: 800 }}>✓</div>}
    </button>
  );
}

Object.assign(window, { BranchSelector });
